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

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

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) =&gt; {
 console.log(Component);
return &lt;Component /&gt;;
};

const BaseTodoList = ({ data = [] }) =&gt; {
  return (
    &lt;ul&gt;
      {data.map((item) =&gt; (
      &lt;div key={Math.random()}&gt;{item}&lt;/div&gt;
     ))}
&lt;/ul&gt;
 );
};

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) =&gt; {
  console.log(Component);
  return () =&gt; &lt;Component /&gt;;
};

答案2

得分: 0

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

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

You can also do as fallows :

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

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:

确定