反应原生onPress事件不在循环中工作

mun*_*eeb 2 javascript reactive-programming hybrid-mobile-app reactjs react-native

我的班级代码

问题是onPress函数如果我在循环中使用它会给出以下错误

onPress={() => this.onPressButton()}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

如果我使用这行代码,没有任何反应

onPress={this.onPressButton}
Run Code Online (Sandbox Code Playgroud)

我知道这必须做一些绑定,我没有得到帮助

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>
  );
}
Run Code Online (Sandbox Code Playgroud)

Mat*_*Aft 5

尝试改变:

Object.keys(randLetters).map(function(key,index) {
Run Code Online (Sandbox Code Playgroud)

至 :

Object.keys(randLetters).map((key,index) => {
Run Code Online (Sandbox Code Playgroud)

您可以在类构造函数中绑定,也可以在渲染中绑定这两种方式

{this.onPressButton.bind(this)}        {() => this.onPressButton()}
Run Code Online (Sandbox Code Playgroud)