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