加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

对象无效作为React子对象(找到:具有键{children}的对象):React

发布时间:2020-12-15 16:18:39 所属栏目:百科 来源:网络整理
导读:const Label = children = ( div className="label"{children}/div);Labelsome text/Label 这给出了一个错误: Objects are not valid as a React child (found: object with keys {children}). If you meant to render a collection of children,use an arr
const Label = children => (
  <div className="label">{children}</div>
);

<Label>some text</Label>

这给出了一个错误:

Objects are not valid as a React child (found: object with keys
{children}). If you meant to render a collection of children,use an
array instead.

什么是正确的方法呢?

解决方法

Reason for Objects are not valid as a React child?

因为这里:

const Label = children => (
   <div className="label">{children}</div>
);

Children只是参数名称,它将具有props的值,它将是一个对象,如下所示:

props = {
   children: .....
}

可能的解决方案:

使用解构并从道具对象中取出孩子,它会起作用.像这样:

const Label = ( {children} ) => (
   <div className="label">{children}</div>
);

或者使用children.children(实际上它将是props.children):

const Label = children => (
   <div className="label">{children.children}</div>
);

检查工作示例(检查控制台日志值,您将获得更好的想法):

const Label1 = (children) => {
   console.log(children);
   return <div className="label">{children.children}</div>
};

const Label2 = ({children}) => {
   console.log(children);
   return <div className="label">{children}</div>
};

ReactDOM.render(<div>
    <Label1>ABC</Label1>
    <Label2>ABC</Label2>
  </div>,document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app'/>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读