首页 文章

touchableopacity onpress函数undefined(不是函数)React Native

提问于
浏览
3

我希望能够在点击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)

任何帮助表示赞赏 .

1 回答

  • 6

    该错误源于您未将 _renderItem 绑定到 this . 将其绑定在 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
    }
    

相关问题