Javascript 调用函数 onPress React Native
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45552957/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Call function onPress React Native
提问by Somename
I just want to know how to call a function onPress. I've setup my code like this:
我只想知道如何调用函数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>
)};
But when I try this, I'm getting error that can't find variable handleClick
但是当我尝试这个时,我收到了错误 can't find variable handleClick
Please help. I just want to know how to bind a function to a click event.
请帮忙。我只想知道如何将函数绑定到点击事件。
回答by evanmcdonnal
In you're render you're setting up the handler incorrectly, give this a try;
在渲染过程中,您错误地设置了处理程序,请尝试一下;
<View>
<Icon
name='heart'
color={this.state.myColor}
size= {45}
style={{marginLeft:40}}
onPress={this.handleClick}
/>
</View>
The syntax you're using would make sense for declaring an anonymous function inline or something but since your handler is defined on the class, you just reference it (not call it) using this.functionNamein the props.
您使用的语法对于声明一个匿名函数内联或其他东西是有意义的,但是由于您的处理程序是在类上定义的,您只需this.functionName在 props 中使用它来引用它(而不是调用它)。
回答by Ray
A little late to the party, but just wanted to leave this here if someone needs it
聚会有点晚了,但如果有人需要,只想把它留在这里
export default class mainScreen extends Component {
handleClick = () => {
//some code
}
render() {
return(
<View>
<Button
name='someButton'
onPress={() => {
this.handleClick(); //usual call like vanilla javascript, but uses this operator
}}
/>
</View>
)};
回答by Miguel Mota
You need to reference the method with the thiskeyword.
您需要使用this关键字来引用该方法。
<Icon
onPress={this.handleClick}
/>
回答by SHREYA PRASAD
you can also try this way of binding
你也可以试试这种绑定方式
this.handleClick = this.handleClick.bind(this)
and put this inside constructor. And while calling use this syntax
并将其放入构造函数中。并在调用时使用此语法
onPress = {this.handleClick}
This will surely solve your problem.
这肯定会解决您的问题。

