问题
I want to be able to navigate to a new screen after tapping the TouchableOpacity button but I receive an error which says
_this3.handleThisTap is not a function. (In '_this3.handleThisTap()','_this3.handleThisTap' is undefined)
import React, { Component } from 'react';
import {
Text,
StyleSheet,
View,
TextInput,
KeyboardAvoidingView,
FlatList,
TouchableOpacity,
TouchableHighlight,
} from 'react-native';
import {
SearchBar,
Wrapper,
ItemWrapper,
} from './searchView.styles';
export default class SearchView extends Component {
constructor(props) {
super(props);
this.state = {
feedUrl: 'https://api.urbandictionary.com/v0/autocomplete?term=',
isLoading: true,
}
}
handleTextChange(text) {
let url = this.state.feedUrl + text;
return fetch(url)
.then((response) => response.json())
.then((res) => {
this.setState({
data: res,
isLoading: false,
})
})
.catch((error) => {
console.log(error);
})
}
handleThisTap(item) {
this.props.navigation.navigate('FeedView', item);
}
_renderItem({ item }) {
return (
<ItemWrapper
underlayColor='white'
onPress={() => this.handleThisTap(item)}>
<Text>{item}</Text>
</ItemWrapper>
)
}
render() {
return (
<Wrapper behavior="padding">
<SearchBar
style={{
shadowOffset: {
width: 0,
height: 5,
},
}}
autoFocus={true}
clearTextOnFocus={true}
placeholder="Search for text here"
returnKeyType='search'
clearButtonMode='always'
keyboardShouldPersistTaps={true}
onChangeText={(text) =>
this.handleTextChange(text)
} />
<FlatList
data={this.state.data}
renderItem={this._renderItem}
/>
</Wrapper>
)
}
}
I have tried using bind.(this)
Any help is appreciated.
回答1:
The error arises from that you didn't bind _renderItem
to this
. Bind it in constructor
:
constructor(props) {
super(props);
this.state = {
feedUrl: 'https://api.urbandictionary.com/v0/autocomplete?term=',
isLoading: true,
}
this._renderItem = this._renderItem.bind(this); //add this line
}
来源:https://stackoverflow.com/questions/44874448/touchableopacity-onpress-function-undefined-is-not-a-function-react-native