【问题标题】:React: Pass function with a given argument to childReact:将具有给定参数的函数传递给孩子
【发布时间】:2021-11-24 07:09:02
【问题描述】:

我的目标是在父组件中创建一个函数并将其传递给子组件,这样我就可以将状态从子组件更新到父组件。

但是,我想已经在父组件中确定一个参数。

有什么办法吗?请参阅下面的示例。

假设我有以下代码

const Parent = ( props ) => {
    
    const [counter, setCounter] = useState(0);

    function updateFunc(type, id) {
        let obj = {type : "", id : id}
        if (type == "red"){
            obj.type = 'RED_FLAG';
        } else {
            obj.type = 'ELSE_FLAG';
        }
    return obj;
    }
    
    return (
        <>
            // HERE I WOULD LIKE TO PASS ALSO A "RED" ARGUMENT -> IS THIS POSSIBLE?
            <Child update = {update}
        </>
    )

}

【问题讨论】:

    标签: javascript reactjs components


    【解决方案1】:

    有一种技术叫做currying。例如,您可以有一个函数,该函数将类型作为参数并返回一个将 id 作为参数的函数,该函数最终返回对象。

    const Parent = (props) => {
    
        const [counter, setCounter] = useState(0);
    
        function updateFunc(type) {
            return (id) => {
                let obj = { type: "", id: id }
                if (type == "red") {
                    obj.type = 'RED_FLAG';
                } else {
                    obj.type = 'ELSE_FLAG';
                }
                return obj;
            }
        }
    
        return (
            <>
                <Child update={update("red")}
            </>
        )
    
    }
    

    【讨论】:

    • 伟大的分析器! currying 似乎是一个不错的技术
    【解决方案2】:

    你可以通过添加一个额外的函数来做到这一点:

    <Child update={(id) => {
      return updateFunc("red", id);
    }}/>
    
    

    【讨论】:

      猜你喜欢
      • 2016-03-19
      • 1970-01-01
      • 2016-12-25
      • 1970-01-01
      • 2020-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-03
      相关资源
      最近更新 更多