React中如何从子组件向父组件传递事件与Props
解决React子组件向父组件同时传递自定义Prop与事件对象的问题
嘿,我明白你拆分展示/容器组件后遇到的困扰了——想在子组件的事件回调里同时传自定义的test-key和原生事件对象给父组件,但之前的bind方式在函数组件里行不通。咱们来一步步修正这个问题:
首先,先找出你现有代码里的两个小问题
- 父组件传递
test函数时,你写的是()=>this.test,这会返回函数本身而非调用它,父组件实际拿到的是一个返回test函数的匿名函数,不是直接的回调。 - 子组件里
onChange={props.test('test-key')}会在组件渲染时立刻执行这个函数,而不是等select的change事件触发时才执行,这显然不是你想要的。
方案一:用箭头函数包裹事件回调(最直接的方式)
这个方法能让你在事件触发时,同时传递自定义key和事件对象:
修改后的父组件代码
class Parent extends Component{ constructor(props) { super(props); this.state = {}; // 这里的bind还是需要的,保证test里的this指向父组件实例 this.test = this.test.bind(this); } test(key, e){ console.log(key, e); // 现在能拿到'test-key'和事件对象了 } render() { // 直接传递绑定好的test函数,不需要额外包裹箭头函数 return <Child test={this.test} /> } }
修改后的子组件代码
// 别忘了接收props参数!你之前的子组件没写props const Child = (props) => { return ( // 用箭头函数包裹,事件触发时再调用props.test,同时传key和e <select onChange={(e) => props.test('test-key', e)}> <option value='1'> Option 1 </option> <option value='2'> Option 2 </option> </select> ) }
方案二:提前在父组件创建绑定了key的回调(适合key固定的场景)
如果这个test-key是父组件已知的固定值,你也可以在父组件里提前生成绑定好参数的回调,子组件直接用即可:
class Parent extends Component{ constructor(props) { super(props); this.state = {}; // 提前绑定好key,子组件不用再传 this.handleTest = this.test.bind(this, 'test-key'); } test(key, e){ console.log(key, e); } render() { return <Child test={this.handleTest} /> } } // 子组件直接传递事件对象就行 const Child = (props) => { return ( <select onChange={props.test}> <option value='1'> Option 1 </option> <option value='2'> Option 2 </option> </select> ) }
为什么之前的bind方式在子组件里失效?
因为你的子组件是函数组件,它没有自己的this上下文,所以props.test.bind(this, 'test-key')里的this是undefined(严格模式下),自然达不到绑定参数的效果。而且就算能绑定,直接写onChange={props.test.bind(...)}会在每次渲染子组件时创建新的函数,虽然不影响功能,但可能有轻微的性能损耗(大部分场景下可以忽略)。
内容的提问来源于stack exchange,提问作者Aurelia Warleader
相关产品推荐
相关产品推荐

