React Native:键盘隐藏事件中Props、Ref值为undefined的问题
问题分析与解决办法
嘿,我一眼就看出问题所在了——你在_keyboardDidHide回调里的this根本没指向组件实例!这就是为什么this.props打印出来是undefined,而且也访问不到this.inputs的原因。另外你构造函数里还漏了super(props),这也是props拿不到的一个关键因素。
给你几个靠谱的解决方案,随便选一个都能解决问题:
方案1:构造函数里绑定this
这是React里最经典的绑定方式,在构造函数里把方法的this牢牢绑定到组件实例上:
constructor(props) { super(props); // 必须加!不然props初始化会出问题 this.inputs = {}; // 绑定this,让回调里的this指向组件 this._keyboardDidHide = this._keyboardDidHide.bind(this); } _keyboardDidHide() { console.log("value", this.props); this.inputs['inputValue'].blur(); } componentWillMount() { this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide); } componentWillUnmount() { this.keyboardDidHideListener.remove(); // 别忘了移除监听,防止内存泄漏 }
方案2:用箭头函数定义回调方法
箭头函数会自动继承外层的this,不用手动绑定,写起来更清爽:
constructor(props) { super(props); this.inputs = {}; } // 直接用箭头函数定义,this自动指向组件实例 _keyboardDidHide = () => { console.log("value", this.props); this.inputs['inputValue'].blur(); } componentWillMount() { this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide); } componentWillUnmount() { this.keyboardDidHideListener.remove(); }
方案3:添加监听时用箭头函数包裹
如果不想改方法定义,也可以在注册监听的时候用箭头函数把回调包起来,确保this正确:
constructor(props) { super(props); this.inputs = {}; } _keyboardDidHide() { console.log("value", this.props); this.inputs['inputValue'].blur(); } componentWillMount() { // 用箭头函数包裹回调,强制this指向组件 this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', () => this._keyboardDidHide()); } componentWillUnmount() { this.keyboardDidHideListener.remove(); }
最后别忘了确认你的TextInput已经正确绑定到this.inputs上,ref属性得这么写:
<TextInput ref={input => this.inputs['inputValue'] = input} // 其他属性... />
内容的提问来源于stack exchange,提问作者Dude
相关产品推荐
相关产品推荐

