React Native中Button组件onPress事件失效问题求助
嘿,我一眼就看出问题所在啦——这是类组件里绑定事件回调的常见小坑!
问题根源
你给Button的onPress属性传的是this._find(),这会导致组件渲染时就立即执行_find函数,而不是把函数本身作为点击回调传递。因为_find函数没有返回值,所以onPress最终拿到的是undefined,这正好对应了你看到的警告:
Warning: Failed prop type: The prop
onPressis marked as required inButton, but its value isundefined.
点击按钮当然没反应啦,因为根本没有有效的回调函数等着被触发!
解决方法
有三种常用的正确写法,选哪种都可以:
1. 直接传递函数引用(需提前绑定this)
首先在构造函数里绑定_find的this指向,确保函数内部的this能正确指向组件实例:
constructor(props) { super(props); this.state = {text: null}; // 绑定this this._find = this._find.bind(this); }
然后修改Button的onPress:
<Button onPress={this._find} title='Find' color="#841584" accessibilityLabel="on" />
2. 使用箭头函数包裹(无需提前绑定)
直接在onPress里用箭头函数包裹你的调用,写法简洁还能保证this指向正确:
<Button onPress={() => this._find()} title='Find' color="#841584" accessibilityLabel="on" />
3. 将_find定义为箭头函数(类字段语法)
如果你用的是支持类字段的语法,可以直接把方法定义成箭头函数,自动绑定this:
_find = () => { fetch('https://google.com') .then((response) => response.text()) .then((text)=>{ console.debug(text) }) }
然后同样用onPress={this._find}即可。
修正后的完整代码示例
这里用第二种方法(箭头函数包裹)展示完整代码:
import React, { Component } from 'react'; import { AppRegistry, Text, TextInput, View,StyleSheet,Button } from 'react-native'; export default class inputText extends Component { _find(){ fetch('https://google.com') .then((response) => response.text()) .then((text)=>{ console.debug(text) }) } constructor(props) { super(props); this.state = {text: null}; } render() { return ( <View style={{margin: 20}}> <TextInput style = {styles.searchInput} placeholder="Type here to search" onChangeText={(text) => this.setState({text})} /> {/* 修正后的onPress写法 */} <Button onPress={() => this._find()} title='Find' color="#841584" accessibilityLabel="on" /> </View> ); } } const styles = StyleSheet.create({ searchInput:{ fontSize:20, paddingTop:20, paddingBottom:20 } }) // skip this line if using Create React Native App AppRegistry.registerComponent('AwesomeProject', () => inputText);
这样修改后,点击按钮就会正常触发_find函数啦!如果以后你的_find需要访问组件的this.state或this.props,记得确保this的指向正确哦~
内容的提问来源于stack exchange,提问作者Александр Зосимчук
相关产品推荐
相关产品推荐

