ReactJS: Why use this.props.children?

前端 未结 4 571
执笔经年
执笔经年 2021-01-01 16:11

I\'ve realised that none of the components I write use {this.props.children}.

I tend to compose my components the way the official docs state at the top

4条回答
  •  一生所求
    2021-01-01 17:09

    In my applications I rarely use this.props.children, because I often know specifically what children I want to render. In libraries, or components written to be re-used outside of a specific component hierarchy, I've seen it often. I think this.props.children has more relevance to that use-case.

    Edit: I thought I'd elaborate on some cases that this.props.children can come in handy. One such example is when creating components which follow the 'render prop' pattern. i.e. I've got some components that require pulling data in from multiple 'render prop' HoC's, such as an Apollo Query component as well as a state management HoC. I combined all my different data sources into one HoC and then called children as a function, passing in the result of pulling out all the data I needed. That being said these days I prefer and look forward to wider adoption of Hooks as an alternative to render props.

    Really any component which you want to render arbitrary children; another example I've used props.children is when creating a HoC that required a user be authenticated before rendering the child, redirecting to a login screen when the user isn't logged in. I could wrap any of my 'protected' screen components with this auth HoC.

    It's still something the majority of my components don't use, but just another tool to be applied when the situation warrants.

提交回复
热议问题