简体   繁体   中英

Is there a way to pass data to props.children in a functional component

I am working a project and want to be able to send data from a component to its props.children component. I think this is done using render props in class components but I don't know how to implement it in a functional one. Here is an extremely simplified version of something I am trying to accomplish. I want to render different things in the Child component depending on what "edit" is set to in Parent.


function Parent({ children }) {
  const [edit, setEdit] = useState(false);
  return (
      <div>
        {"blah blah blah..."}
        <button onClick={()=>{setEdit(!edit)}}>Click</button>
      {children}
      </div>
  );
}

function Child() {
  if (edit === true) {
    return (
      <Parent>
        {"Edit is True"}
      </Parent>
    );
  }

  return (
    <Parent>
      {"Edit is False"}
    </Parent>
  );
}

You have to generate children components by cloning elements manually.

How to pass props to {this.props.children}

Is this what you need? You can share states to children

const Parent = () => {
 const [edit, setEdit] = useState(true);
  return (
    <>
      <div>Hello</div>
      <Child edit={edit} />
    </>
  );
};

const Child = params => {
  return params.edit? (
    <div>Do something if true</div>
  ):
  (
    <div>Do something if false</div>
  )
};

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