2017-08-25 243 views
0

我试图将函数​​绑定到我的按钮onPress。但它不起作用。当我刷新页面时,无需点击按钮即可获得警报,在关闭警报并单击按钮后,什么都不会发生。React-Native按钮onPress不工作

我的代码是:

class ActionTest extends Component { 
    constructor(props) { 
    super(props); 
    this.state = { 
     thename: 'somename' 
    }; 
    } 

    handleClick(){ 
    alert('Button clicked!'); 
    } 

    render(){ 
     return(
     <View> 
      <Button 
      onPress={this.handleClick()} 
      title="Click ME" 
      color="blue" 
      /> 
     </View> 
     ); 
    } 
} 

我也得到警告:

enter image description here

我在做什么错?

+0

要调用的handleclick功能,当组件呈现你想要做onPress = {this.handleClick}'这样这将是一个回调,并且只会在onpress触发时运行该函数 –

回答

3

要调用handleClick当它呈现为你onPress={this.handleClick()}

尝试onPress={this.handleClick}而是通过它的函数作为回调。

1

更新您的代码!你应该通过一个参考

<Button 
     onPress={this.handleClick} 
     title="Click ME" 
     color="blue" 
     /> 
4

首先你定义你的点击处理程序为一个箭头函数。这样你就不需要再绑定这个函数了。你的函数将是这样的:

<Button 
onPress={this.handleClick} 
title="Click ME" 
color="blue" 
/> 
3

当反应本土检测到点击事件而需要通知你,它会调用onPress

handleClick =() => { 
    alert('Button clicked!'); 
} 

然后在<Button>标签这样使用此功能道具作为一种功能。所以你必须给功能onPress道具,如:

onPress={this.handleClick} 

这个连接onPress到​​方法。但如果你想调用其他方法​​,你需要“this对象”,你可以通过​​方法是这样的:

onPress={this.handleClick.bind(this)} 

好运