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

时间:2018-12-23 10:45:59

标签: javascript reactjs web

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

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

如果是,该怎么办?

2 个答案:

答案 0 :(得分:2)

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

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

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

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

希望能回答您的问题。

答案 1 :(得分:1)

替代 Ashish 的答案,您可以使用以下方法解构子组件中的“children”属性:

const FunctionalComponent = ({ children }) => {
  return (
    <div>
      <div>I am inside functional component.</div>
      { children }
    </div>
  );
};

这将允许您传递其他您想要解构的道具。

const FunctionalComponent = ({ title, content, children }) => {
  return (
    <div>
      <h1>{ title }</h1>
      <div>{ content }</div>
      { children }
    </div>
  );
};

您仍然可以使用“props.title”等来访问那些其他道具,但它不太干净并且没有定义您的组件接受什么。