【问题标题】:How to access props.children in a stateless functional component in react?如何在反应中访问无状态功能组件中的 props.children?
【发布时间】:2019-05-22 23:56:32
【问题描述】:

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

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

如果有,怎么办?

【问题讨论】:

  • 请进一步解释您的情况。你想达到什么目的?一个可行的例子会有所帮助。我看不出有状态/无状态的东西会如何影响children prop。

标签: javascript reactjs web


【解决方案1】:

我们可以在功能组件中使用 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>
  );
};

希望能回答你的问题。

【讨论】:

  • 如果你想以 ES6 方式解构对象,我会添加它____const NewComponent = ({ children }) =&gt; &lt;div&gt; {children} &lt;/div&gt;
【解决方案2】:

除了 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”等来访问这些其他道具,但它不太干净并且没有定义您的组件接受什么。

【讨论】:

    猜你喜欢
    • 2022-11-21
    • 1970-01-01
    • 1970-01-01
    • 2021-05-13
    • 1970-01-01
    • 2022-06-27
    • 2022-09-30
    • 1970-01-01
    • 2020-09-09
    相关资源
    最近更新 更多