簡體   English   中英

未處理的JS異常:TyperError:未定義不是對象(正在評估'_this.onPress.bind')

[英]Unhandled JS Exception: TyperError: undefined is not an object (evaluating '_this.onPress.bind')

我正在嘗試使用TouchableOpacity的onPress在React Native中創建一個按鈕。 我以前可以使用它,但是現在我在“喜歡”函數中添加了一些額外的功能,它不再起作用。

onPress應使用函數提供參數。

我收到錯誤Unhandled JS Exception: TyperError: undefined is not an object (evaluating '_this.onPress.bind')我的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> ); } } 

暫無
暫無

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

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