我只想知道如何调用函数onPress
。我已经像这样设置了我的代码:
export default class Tab3 extends Component {
constructor(props) {
super(props);
this.state = {myColor: "green"};
}
handleClick = () => {
if (this.state.color === 'green'){
this.setState({myColor: 'blue'});
} else {
this.setState({myColor: 'green'});
}
}
render() {
return(
<View>
<Icon
name='heart'
color={this.state.myColor}
size= {45}
style={{marginLeft:40}}
onPress={() => handleClick(this)}
/>
</View>
)};
但是当我尝试这个时,我得到了错误,找不到变量 handleClick
请帮忙。我只想知道如何将函数绑定(bind)到点击事件。
最佳答案
在渲染中,您设置的处理程序不正确,请尝试一下;
<View>
<Icon
name='heart'
color={this.state.myColor}
size= {45}
style={{marginLeft:40}}
onPress={this.handleClick}
/>
</View>
您使用的语法对于声明匿名函数内联或其他内容是有意义的,但由于您的处理程序是在类上定义的,您只需使用 this.functionName
引用它(而不是调用它)在 Prop 中。
关于javascript - 调用函数 onPress React Native,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45552957/