React Native中作为Prop传递的箭头函数在子组件中为undefined的问题
解决CreateGroup容器组件传递handleChange函数到展示组件的问题
先排查基础错误
检查属性接收层级:确认展示组件
CreateGroupPresentation是从正确层级获取handleChange。如果容器是把函数放在presentationProps对象里传递,展示组件就得从props.presentationProps里解构,不能直接从外层props拿:// 展示组件正确写法 const CreateGroupPresentation = ({ presentationProps }) => { const { handleChange } = presentationProps; return <TextInput onChange={handleChange} />; };要是容器直接把
handleChange作为单独属性传递,那展示组件直接从外层props解构即可。核对拼写大小写:检查容器里传递的属性名是不是
handleChange(注意大小写),展示组件里取的时候有没有写错,比如写成handlechange会直接返回undefined。
不修改容器组件函数体的修复方案
如果问题出在类组件中handleChange未绑定this,导致传递后变成undefined,又不想改动handleChange的函数体内容,可以用这两种方法:
方法1:在render里用箭头函数包裹传递
在容器组件的render方法中,给handleChange套一层箭头函数,自动绑定当前组件的this:
// 容器组件的render部分 render() { const presentationProps = { // 用箭头函数绑定this,不修改原handleChange函数体 handleChange: (...args) => this.handleChange(...args), handleSubmit: this.handleSubmit }; return <CreateGroupPresentation presentationProps={presentationProps} />; }
方法2:在构造函数中绑定this
如果是类组件,在构造函数里提前给handleChange绑定this,这也不会改动handleChange的函数逻辑:
// 容器组件的构造函数 constructor(props) { super(props); // 绑定this,不修改原函数体 this.handleChange = this.handleChange.bind(this); } render() { const presentationProps = { handleChange: this.handleChange, handleSubmit: this.handleSubmit }; return <CreateGroupPresentation presentationProps={presentationProps} />; }
函数式容器组件的注意点
如果容器是函数式组件,只要handleChange是正确定义的箭头函数或普通函数,直接传递就行,不会有this绑定问题:
const CreateGroup = () => { // 正确定义handleChange const handleChange = (text) => { // 处理输入逻辑 }; const presentationProps = { handleChange, handleSubmit: () => {} }; return <CreateGroupPresentation presentationProps={presentationProps} />; };
内容的提问来源于stack exchange,提问作者Jonathan Potter
相关产品推荐
相关产品推荐

