JSX字面量和组件之间有什么区别?React.jsx:类型无效– 期望一个字符串

huangapple go评论94阅读模式
英文:

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

  1. const withHigherOrderComponent = (Component) =&gt; {
  2. console.log(Component);
  3. return &lt;Component /&gt;;
  4. };
  5. const BaseTodoList = ({ data = [] }) =&gt; {
  6. return (
  7. &lt;ul&gt;
  8. {data.map((item) =&gt; (
  9. &lt;div key={Math.random()}&gt;{item}&lt;/div&gt;
  10. ))}
  11. &lt;/ul&gt;
  12. );
  13. };
  14. const TodoList = withHigherOrderComponent(BaseTodoList);
  15. export default TodoList;

答案1

得分: 3

你的高阶组件(HOC)没有返回一个组件(应该是一个函数或类),而是调用了传入的组件并返回结果。

应该是

  1. const withHigherOrderComponent = (Component) => {
  2. console.log(Component);
  3. return () => <Component />;
  4. };
英文:

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

  1. const withHigherOrderComponent = (Component) =&gt; {
  2. console.log(Component);
  3. return () =&gt; &lt;Component /&gt;;
  4. };

答案2

得分: 0

你也可以按照以下方式操作:

  1. const withHigherOrderComponent = (Component) => () => {
  2. console.log(Component);
  3. return <Component />;
  4. };
  5. 语法将取决于是否使用类或函数以及返回内容和高阶组件参数的可读性
英文:

You can also do as fallows :

  1. const withHigherOrderComponent = (Component) =&gt; () =&gt; {
  2. console.log(Component);
  3. return &lt;Component /&gt;;
  4. };

Syntax will depend, if class or function is used and readability on return content and HOC parameters.

huangapple
  • 本文由 发表于 2023年1月8日 23:19:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/75048933.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定