簡體   English   中英

反應本機onPress事件無法循環

[英]react native onPress event not working in loop

我的班級代碼

問題是onPress函數,如果我在循環中使用它,則出現以下錯誤

onPress={() => this.onPressButton()}

在此處輸入圖片說明

如果我使用此行代碼,則不會發生任何事情

onPress={this.onPressButton}

我知道這與綁定有關,我沒有得到幫助

export default class PlayGame extends Component {

  navigate(routName){
    this.props.navigator.push({
     name:  routName
   })
  }

  onPressButton() {
    alert("You tapped the button!");
  }

  render() {
    //var selectedLetter = Globals.URDU_ALPHABETS[Math.floor(Math.random()*Globals.URDU_ALPHABETS.length)];  //will be used when app is MVP
    //add selected array

    var selectedLetter = Globals.URDU_ALPHABETS[1];
    var randLetters =  shuffle(randomLetters(Globals.URDU_ALPHABETS,selectedLetter));
    playSelectedLetter(selectedLetter.name);      
    return (             
     <View style={{flex: 3,backgroundColor: 'silver', flexDirection: 'column', justifyContent:'space-between', alignItems: 'center'}}>                      
     <View style={{width: 400, height: 8, flex: 1, backgroundColor: 'steelblue'}}  /> 
     <View style={{flex: 3,backgroundColor: 'silver', flexDirection: 'row', justifyContent:'space-between', alignItems: 'center'}}>

     {Object.keys(randLetters).map(function(key,index) {   

       return <TouchableHighlight key={index} letterName={randLetters[key].name} onPress={() => this.onPressButton()} > 
       <View style={{width: 50, height: 50, backgroundColor: 'skyblue'}} key={index}><Text key={index} >{randLetters[key].name}</Text></View> 
       </TouchableHighlight>

     }
     )}
     </View>     
     <TouchableHighlight onPress={this.onPressButton}>
     <Text>Button</Text>
     </TouchableHighlight>
     <View style={{width: 0, height: 0, backgroundColor: 'skyblue'}}><Text></Text></View>             
     </View>
  );
}

嘗試更改:

Object.keys(randLetters).map(function(key,index) {

至 :

Object.keys(randLetters).map((key,index) => {

您可以在類構造函數中綁定,也可以在呈現器中綁定這兩種方式

{this.onPressButton.bind(this)}        {() => this.onPressButton()}

您必須將其綁定到組件上下文:

export default class PlayGame extends Component {

    constructor(props) {
        super(props);

        this.onPressButton = this.onPressButton.bind(this)
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM