通过道具发送对象属性时无法渲染组件

时间:2021-07-13 08:34:47

标签: javascript reactjs

下面一切正常

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.

我做错了什么?

3 个答案:

答案 0 :(得分:2)

您正在嵌入 author.id,它是表达式中的一个对象,这就是它显示的原因

<块引用>

对象作为 React 子对象无效(找到:带有键 {title} 的对象)。如果您打算渲染一组子项,请改用数组。

您可以在 JSX 中解构 title 或直接使用 title

codesandbox

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