4

我希望能够在点击 TouchableOpacity 按钮后导航到新屏幕,但我收到一条错误消息

_this3.handleThisTap 不是一个函数。(在 '_this3.handleThisTap()' 中,'_this3.handleThisTap' 未定义)

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>
    )
  }
}

我试过使用bind.(this)

任何帮助表示赞赏。

4

1 回答 1

7

错误源于您没有绑定_renderItemthis. 将其绑定在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
}
于 2017-07-02T20:11:58.547 回答