最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to access props.children in a stateless functional component in react? - Stack Overflow

programmeradmin1浏览0评论

The functional components in react are better to use if there aren't any internal state to be tracked within the component.

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. Is this possible ?

If so , how to do it ?

The functional components in react are better to use if there aren't any internal state to be tracked within the component.

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. Is this possible ?

If so , how to do it ?

Share Improve this question asked Dec 23, 2018 at 10:45 Natesh bhatNatesh bhat 13.2k12 gold badges93 silver badges131 bronze badges 1
  • Please explain your case further. What are you trying to achieve? A workable example would help. I don't see how stateful/stateless thing can affects children prop. – Estus Flask Commented Dec 23, 2018 at 10:50
Add a comment  | 

2 Answers 2

Reset to default 31

We can use props.children in functional component. 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:

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.

发布评论

评论列表(0)

  1. 暂无评论