简体   繁体   中英

Get children of React.Fragment

I'm returning React.Fragment in my component:

render() {
  return (
    <Fragment>
      <MyFirstElement/>
      <MySecondElement/>
    </Fragment>

Now I want to process all children in the parent component. I can get the Fragment component itself via this.props.children .

My Question

But how can I get the children of the Fragment component so that I can also process the children of Fragment ?

If you want to 'edit' the children passed to a component, the best option is to create a custom component in which you have full control over the children.

Since the component only returns its children, it behaves like a Fragment

Small example to demonstrate this"

  1. <Parent /> returns a <CustomFragment> with 2 <Child /> components
  2. The <Child /> component expects a testProp value, but <Parent /> does not provide it
  3. In our <CustomFragment> we map() through our children, to add the testProp expected by <Child />

 class Parent extends React.Component { render() { return ( <CustomFragment> <Child /> <Child /> </CustomFragment> ); } } class Child extends React.Component { render() { return <p>{`Deep #${this.props.testProp}`}</p> } } class CustomFragment extends React.Component { render() { // Render children return this.props.children.map((child) => { // Change child if needed // For example, lets add a testProp child.props['testProp'] = Math.floor(Math.random() * 10) + 1 // Return return child; }); } } ReactDOM.render(<Parent />, document.body);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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