我已经从react native的快速入门指南中略微更改了默认的App.js,我尝试创建一个计数器,每次按下屏幕中间的按钮时,计数器从1开始计数。运行以下代码时,出现此错误:Warning: Failed prop type: The prop 'onPress' is marked as required in 'Button', but its value is 'undefined'....
问题是它无法识别函数this.onButtonPress()
中的renderButton = () => {}
。我认为关键字this
可能是一个问题,因为我听说这指向父函数而不是父对象,但是我认为这应该仍然有效...我不确定为什么没有。任何帮助将不胜感激,谢谢!
import React, { Component } from 'react';
import {
Platform,
StyleSheet,
Text,
View,
Button
} from 'react-native';
const instructions = Platform.select({
ios: 'Press Cmd+R to reload,\n' +
'Cmd+D or shake for dev menu',
android: 'Double tap R on your keyboard to reload,\n' +
'Shake or press menu button for dev menu',
});
export default class App extends Component<Props> {
constructor(props) {
super(props);
this.state = {
count: 1
};
}
renderButton = () => {
return(
<Button
onPress={this.onButtonPress()}
title="BUTTON"
color="#841584"
/>
);
}
onButtonPress = () => {
var previous = this.state.count;
this.state.count = previous + 1;
}
render = () => {
return (
<View style={styles.container}>
{this.renderButton()}
<Text style={styles.welcome}>
Count: {this.state.count}
</Text>
<Text style={styles.instructions}>
To get started, edit App.js
</Text>
<Text style={styles.instructions}>
{instructions}
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
答案 0 :(得分:1)
您正在调用该函数,而不是传递引用。
renderButton = () => {
return(
<Button
onPress={this.onButtonPress} // <-- you were invoking the function here instead of passing the reference
title="BUTTON"
color="#841584"
/>
);
}
或者,您可以传递一个匿名函数来调用您的方法。
renderButton = () => {
return(
<Button
onPress={() => this.onButtonPress()}
title="BUTTON"
color="#841584"
/>
);
}
React认为它是undefined
的原因是因为函数执行没有返回值,因此返回了undefined
。您的函数立即运行,而不是在onPress
事件之后运行。因此,React将函数的结果用作onPress
事件处理程序,而不是函数本身。
答案 1 :(得分:1)
在React中更新状态时,您想使用setState。下面是使用您的代码的示例:
onButtonPress = () => {
var newCount = this.state.count + 1;
this.setState({
count: newCount
});
}