如何将道具传递给组件的孩子

时间:2019-06-10 15:26:48

标签: javascript reactjs

const ListView = () => {
  return(
    <ul>
      <ListItem modal={<Modal />} />
    </ul>
  )
};

const ListItem = (props) => {
  const [visible, setVisible] = useState(false);
  const toggle = () => setVisible(!visible)

  return (
    <>
      <li>
        ListItem 
      </li>
      <ModalWrapper toggle={toggle}>{props.modal}</ModalWrapper>
    </>
  )
}

const ModalWrapper = (props) => {
  if(!props.visible) return null;
  return (
    <>
      {props.children}
    </>
  )
}

const Modal = ({ toggle }) => {
  /* I would like to use toggle() here. */
  return (
    <>
      <div onClick={toggle} className="dimmer"></div> 
      <div className="modal">modal</div>
    </>
  )
}

如上所述,我在toggle()中有一个函数<ListItem />

我正在努力在toggle()中使用<Modal />

有可能还是有任何建议?

1 个答案:

答案 0 :(得分:1)

您需要向toggle的孩子注入ModalWrapper,请注意不要覆盖toggle上的Modal道具。

const ModalWrapper = ({ children, visible, toggle }) => {
  const injected = React.Children.map(children, child =>
    React.cloneElement(child, { toggle })
  );
  return <>{visible && injected}</>;
};

请参阅React.cloneElementReact.Children.map

演示:

Edit SO-Q-56529259