英文:
What is difference between JSX literal and a component? React.jsx: type is invalid -- expected a string
问题
错误: 警告:React.jsx:类型无效 - 期望一个字符串(用于内置组件)或一个类/函数(用于组合组件),但得到了:<BaseTodoList />。您是否意外导出了一个JSX文字而不是一个组件?
在App
const withHigherOrderComponent = (Component) => {
console.log(Component);
return <Component />;
};
const BaseTodoList = ({ data = [] }) => {
return (
<ul>
{data.map((item) => (
<div key={Math.random()}>{item}</div>
))}
</ul>
);
};
const TodoList = withHigherOrderComponent(BaseTodoList);
export default TodoList;
英文:
Error: Warning: React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: <BaseTodoList />. Did you accidentally export a JSX literal instead of a component?
at App
const withHigherOrderComponent = (Component) => {
console.log(Component);
return <Component />;
};
const BaseTodoList = ({ data = [] }) => {
return (
<ul>
{data.map((item) => (
<div key={Math.random()}>{item}</div>
))}
</ul>
);
};
const TodoList = withHigherOrderComponent(BaseTodoList);
export default TodoList;
答案1
得分: 3
你的高阶组件(HOC)没有返回一个组件(应该是一个函数或类),而是调用了传入的组件并返回结果。
应该是
const withHigherOrderComponent = (Component) => {
console.log(Component);
return () => <Component />;
};
英文:
your HOC does not return a component (which should be a function
or Class
), but it calls the passed component and returns the result.
It should be
const withHigherOrderComponent = (Component) => {
console.log(Component);
return () => <Component />;
};
答案2
得分: 0
你也可以按照以下方式操作:
const withHigherOrderComponent = (Component) => () => {
console.log(Component);
return <Component />;
};
语法将取决于是否使用类或函数,以及返回内容和高阶组件参数的可读性。
英文:
You can also do as fallows :
const withHigherOrderComponent = (Component) => () => {
console.log(Component);
return <Component />;
};
Syntax will depend, if class or function is used and readability on return content and HOC parameters.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论