【问题标题】:React and React Hooks: Using an onClick function in a child to fire a function of a parent wrapping componentReact 和 React Hooks:在子组件中使用 onClick 函数来触发父包装组件的函数
【发布时间】:2020-12-29 01:02:27
【问题描述】:

我有一个包装器组件,它根据自己的状态 (isDeleted) 有条件地呈现它的子组件。基本上我有一个“可删除项目”组件,如果单击按钮删除,项目本身将从 DOM 中删除(通过返回一个空的 ReactNode,即 >)。问题是,我不知道如何将显示为包装器子级的按钮单击事件传递到被包装组件本身:

export default function App() {
    return (
        <DeleteableItemComponent>
            {/* lots of other markup here */}
            <button onClick={triggerFunctionInsideDeletableItemComponent}>
        </DeleteableItemComponent>
    )
}

以及我的可删除项目组件的最基本版本:

export default function DeleteableItemComponent() {
    const [isDeleted, setIsDeleted] = useState(false);

    const functionIWantToFire = () => {
        // call API here to delete the item serverside; when successful, 'delete' on frontend
        setIsDeleted(true)
    }

    if (isDeleted) {
        return <></>
    }

    return <>{children}</>
}

所以很简单,我只想从按钮onClick 回调中调用functionIWantToFire

如何通过钩子正确地做到这一点?我曾考虑过使用上下文 API,但我从未见过它用于触发函数触发,仅用于设置值,在这种情况下,我想触发事件本身,而不是将特定值传达给包装器组件。我也不能通过仅仅传递一个布尔属性来正确地做到这一点,因为那时我只能设置一次,即从falsetrue

【问题讨论】:

    标签: reactjs react-hooks react-functional-component higher-order-components


    【解决方案1】:

    您可以使用React.cloneElement API 将道具传递给您的孩子,同时使用React.children.map 进行迭代。

    React.Children.map(children, (child) => {
       return React.cloneElement(child, { /* .. props here */ });
    });
    

    一个简单的例子就是。 您可以查看示例here

    
    function App() {
      return (
       <Delete>
          <Child1 />
          <Child2 />
       </Delete>
      );
    }
    
    function Delete({ children }) {
      const [clicked, setClicked] = React.useState(0);
    
      const inc = () => setClicked(clicked + 1);
      const dec = () => setClicked(clicked - 1);
    
      return React.Children.map(children, (child) => {
        return React.cloneElement(child, { inc, clicked, dec });
      });
    }
    
    
    function Child1(props) {
      return ( 
        <div>
          <p>{props.clicked}</p>
          <button onClick={props.inc}>Inc</button>
        </div>
      )
    }
    
    function Child2(props) {
      return ( 
        <div>
          <button onClick={props.dec}>Dec</button>
        </div>
      )
    }
    
    

    【讨论】:

      猜你喜欢
      • 2020-02-22
      • 1970-01-01
      • 1970-01-01
      • 2017-04-15
      • 1970-01-01
      • 2022-01-15
      • 2020-10-26
      • 2020-05-30
      • 2015-11-09
      相关资源
      最近更新 更多