如何在无状态功能组件中访问props.children做出反应?

Nat*_*hat 2 javascript web reactjs

如果组件中没有任何内部状态要跟踪,则react中的功能组件最好使用。

但是我想要的是访问children无状态组件,而不必扩展React.Component我可以使用的组件props.children。这可能吗 ?

如果是这样,该怎么办?

小智 7

我们可以在功能组件中使用props.children。无需使用基于类的组件。

const FunctionalComponent = props => {
  return (
    <div>
      <div>I am inside functional component.</div>
      {props.children}
    </div>
  );
};
Run Code Online (Sandbox Code Playgroud)

调用功能组件时,可以执行以下操作-

const NewComponent = props => {
  return (
    <FunctionalComponent>
      <div>this is from new component.</div>
    </FunctionalComponent>
  );
};
Run Code Online (Sandbox Code Playgroud)

希望这能回答你的问题。

  • 如果你想以 ES6 方式解构对象,我会添加这个 ____ `const NewComponent = ({ children }) =&gt; &lt;div&gt; {children} &lt;/div&gt; ` (2认同)