简体   繁体   English

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

[英]How to access props.children in a stateless functional component in react?

The functional components in react are better to use if there aren't any internal state to be tracked within the component.如果组件内没有任何内部状态要跟踪,则最好使用 React 中的功能组件。

But what I want is to access the children of the stateless components without having to extend React.Component using which i can use props.children .但我想要的是访问无状态组件的children组件,而不必扩展我可以使用React.Componentprops.children Is this possible?这可能吗?

If so, how to do it?如果可以,该怎么做?

We can use props.children in functional component.我们可以在功能组件中使用 props.children。 There is no need to use class based component for it.不需要为此使用基于类的组件。

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

When you will call the functional component, you can do as follows -当您调用功能组件时,您可以执行以下操作 -

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

Hope that answers your question.希望这能回答你的问题。

Alternatively to the answer by Ashish, you can destructure the "children" property in the child component using:除了 Ashish 的回答之外,您还可以使用以下方法解构子组件中的“children”属性:

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

This will allow you to pass along other props that you would like to destructure as well.这将允许您传递其他您想要解构的道具。

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

You can still use "props.title" etc to access those other props but its less clean and doesn't define what your component accepts.您仍然可以使用“props.title”等来访问其他道具,但它不太干净并且没有定义您的组件接受的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM