React中如何通过点击事件将数据从子函数组件传递到父类组件
问题分析与调整方案
你代码的核心问题是回调函数传递时错误地直接执行了函数,而非传递函数引用给子组件触发,共两处核心需要调整,同时还存在基础的JSX结构遗漏问题:
1. 父组件调整点
原代码中给MultiSelect传updateProfile属性时,写了updateProfile(),相当于组件渲染时直接执行了这个方法,把执行后的返回值(此处为undefined)传给了子组件,正确写法是传递绑定好的函数引用this.updateProfile。另外类组件的JSX必须放在render方法的return内,原代码遗漏了这部分结构。
修正后的父组件核心代码:
export default class ProfileEditor extends React.Component<IProfileEditorProps, IProfileEditorState> { constructor(props: IProfileEditorProps) { super(props); this.state = { data: null, } this.updateProfile = this.updateProfile.bind(this); } public updateProfile(director, nonDirector) { console.log('hello', director, nonDirector); // 后续处理数据的逻辑可写在这里 } // 补上类组件必须的render方法 render() { return ( <MultiSelect options={ profile?.Declarations.length == 0 ? countries : this.combineProfileAndCountrys() } updateProfile={this.updateProfile} {/* 不要加括号,传函数引用即可 */} /> ) } }
2. 子组件调整点
原代码中按钮的onClick直接写了updateProfile(nonDirector, director),相当于子组件渲染时就直接执行了父组件传过来的方法,而非点击时才触发。正确写法是把执行逻辑包装成箭头函数,点击时才执行传参调用。另外函数组件的JSX必须放在return内,原代码也遗漏了这部分结构。
修正后的子组件核心代码:
export const MultiSelect = ({ options, updateProfile }) => { const [nonDirector, setNonDirector] = React.useState(); const [director, setDirector] = React.useState(); // 补上函数组件必须的return语句 return ( <Fragment> {/* 此处省略你自己的选择器交互逻辑 */} <PrimaryButton text='Save' onClick={() => updateProfile(nonDirector, director)} {/* 用箭头函数包装,点击时才执行传参 */} /> </Fragment> ) }
调整完成后,点击子组件的Save按钮,就能正常把两个state的值传递到父组件的updateProfile方法中。
内容的提问来源于stack exchange,提问作者BennKingy
相关产品推荐
相关产品推荐

