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

对象无效作为React子对象(找到:具有键{children}的对象):ReactJS (Objects are not valid as a React child (found: object with keys {children}): ReactJS)

2017-10-29 reactjs

问题

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

<Label>some text</Label>

这给出了一个错误:

对象无效作为React子对象(找到:具有键{children}的对象)。如果您要渲染子集合,请使用数组。

什么是正确的方法呢?

解决方法

对象的原因作为React孩子无效?

因为这里:

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'/>


问题

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

<Label>some text</Label>

This gives an error:

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.

What's the right way to do it?

解决方法

Reason for Objects are not valid as a React child?

Because here:

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

Children is just the argument name, it will have the values of props, and it will be an object, like this:

props = {
   children: .....
}

Possible Solutions:

Use destructuring and take out the children from props objects, it will work. Like this:

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

Or use children.children (actually it will be props.children):

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

Check working example (check the console log values you will get the better idea):

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'/>

相似信息