2017-08-25 52 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)} 

好運