下面一切正常
const test = {
title: "test title"
};
export default function App() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<p>{test.title}</p>
</div>
);
}
但是如果我尝试渲染一个从 Test
接收 title
道具的 test.title
组件,如下所示
const test = {
title: "test title"
};
const Test = (title) => {
return (
<article>
<h4>{title}</h4>
</article>
);
};
export default function App() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<p>{test.title}</p>
<Test title={test.title} />
</div>
);
}
我收到错误
Objects are not valid as a React child (found: object with keys {title}). If you meant to render a collection of children, use an array instead.
我做错了什么?
答案 0 :(得分:2)
您正在嵌入 author.id
,它是表达式中的一个对象,这就是它显示的原因
对象作为 React 子对象无效(找到:带有键 {title} 的对象)。如果您打算渲染一组子项,请改用数组。
您可以在 JSX 中解构 title
或直接使用 title
props.title
或
const Test = (props) => {
return (
<article>
<h4>{props.title}</h4>
</article>
);
};
答案 1 :(得分:1)
道具作为 object
传递到组件中,因此您的标题在 props.title
const Test = (props) => {
return (
<article>
<h4>{props.title}</h4>
</article>)};
答案 2 :(得分:0)
当尝试将 props 作为对象发送时,应该销毁对象或直接使用 props.title