React如何将预指定参数的父组件函数传给子组件以更新状态
完全可以实现,常见有两种实现方案:
方案1:箭头函数包装(函数式组件优先推荐)
直接在传参时用箭头函数包裹逻辑,预先填入固定参数,子组件调用时只需要传递剩下的动态参数即可,写法更直观。
修改后的父组件代码示例:
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'; } // 补充你自己的state更新逻辑即可 return obj; } return ( <> {/* 预先固定第一个参数为"red",子组件调用时仅需传入id参数 */} <Child update={(id) => updateFunc("red", id)} /> </> ) }
子组件内调用示例:
const Child = ({update}) => { // 调用时只需要传id即可,对应父组件预先填好的type参数 return <button onClick={() => update(1001)}>触发更新</button> }
方案2:使用Function.prototype.bind
用bind方法预先绑定参数,第一个参数为this指向(函数式组件无实例this,填null即可),后续参数为要预先固定的入参,效果和箭头函数包装完全一致:
<Child update={updateFunc.bind(null, "red")} />
性能优化注意事项
如果Child组件做了memo优化,直接写行内箭头函数/bind会导致每次父组件渲染时生成新的函数引用,触发子组件不必要的重渲染,这种情况可以配合useCallback缓存函数:
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; } // 用useCallback缓存函数引用,避免不必要重渲染 const boundUpdate = useCallback((id) => updateFunc("red", id), []) return ( <> <Child update={boundUpdate} /> </> ) }
内容的提问来源于stack exchange,提问作者employee
相关产品推荐
相关产品推荐

