gpt4 book ai didi

javascript - react native onPress 事件不在循环中工作

转载 作者:行者123 更新时间:2023-11-29 16:46:18 33 4
gpt4 key购买 nike

我的类(class)代码

problem is onPress function give the following error if i use it in the loop

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

enter image description here

nothing happens if i use this line of code

onPress={this.onPressButton}

I know this has to do something with binding which i am not getting kindly help

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) => {

可以在类构造函数中绑定(bind),也可以在render中用这两种方式绑定(bind)

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

关于javascript - react native onPress 事件不在循环中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41044834/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com