我正在尝试使用TouchableOpacity的onPress在React Native中制作一个按钮。我之前让它工作,但现在我在函数"like"中添加了一些额外的功能,它不再工作了。
onPress 应该给出一个带有函数的参数。
我在iOS模拟器中收到错误Unhandled JS Exception: TyperError: undefined is not an object (evaluating '_this.onPress.bind')
。
我的代码:
export default class App extends Component {
constructor(props) {
super(props)
this.state = { liked: [false, false, false] }
this.onPress = this.onPress.bind(this)
}
like = (id) => {
const liked = this.state.liked
liked[id] = !liked[id]
this.setState({
liked: [!this.state.liked[0], false, false ],
});
}
render() {
return (
<Swiper style={SliderStyles.wrapper} showsButtons={false}>
<View style={SliderStyles.slide1}>
<View style={CardStyles.card}>
<View style={CardStyles.card_img} >
<Image source={require('./recources/ny.jpg')} style={CardStyles.images}/>
</View>
<View style={CardStyles.card_details}>
<Text style={TextStyles.card_title} >New York</Text>
<View style={CardStyles.card_action}>
<TouchableOpacity style={CardStyles.card_button} onPress={() => this.like(0)}>
<Image source={ this.state.liked[0] === true ?
require('./recources/icons/heart_closed.png') :
require('./recources/icons/heart_open.png')
} style={CardStyles.card_button_img}/>
</TouchableOpacity>
</View>
<Text style={TextStyles.card_name}>Seppe De Langhe</Text>
</View>
</View>
</View>
</View>
</Swiper>
);
}
}
我的iOS模拟器的外观图片
感谢您的帮助!
看起来您没有要绑定的onPress
方法,您的方法称为like
并且由于您使用的是箭头函数,因此它已绑定。
export default class App extends Component {
state = {
liked: [false, false, false],
};
like = (id) => {
this.setState(state => {
state.liked[id] = !state.liked[id];
return state;
});
}
render() {
return (
<Swiper style={SliderStyles.wrapper} showsButtons={false}>
<View style={SliderStyles.slide1}>
<View style={CardStyles.card}>
<View style={CardStyles.card_img} >
<Image source={require('./recources/ny.jpg')} style={CardStyles.images}/>
</View>
<View style={CardStyles.card_details}>
<Text style={TextStyles.card_title} >New York</Text>
<View style={CardStyles.card_action}>
<TouchableOpacity style={CardStyles.card_button} onPress={() => this.like(0)}>
<Image source={ this.state.liked[0] === true ?
require('./recources/icons/heart_closed.png') :
require('./recources/icons/heart_open.png')
} style={CardStyles.card_button_img}/>
</TouchableOpacity>
</View>
<Text style={TextStyles.card_name}>Seppe De Langhe</Text>
</View>
</View>
</View>
</View>
</Swiper>
);
}
}