代码之家  ›  专栏  ›  技术社区  ›  Natesh bhat

如何访问react中无状态功能组件中的props.children?

  •  0
  • Natesh bhat  · 技术社区  · 6 年前

    children 无状态组件的扩展 React.Component 用我能用的 props.children

    1 回复  |  直到 6 年前
        1
  •  26
  •   Ashish    6 年前

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

    希望这能回答你的问题。

        2
  •  1
  •   John    4 年前

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