【问题标题】:Problem with indirect communication between parent and child elements父子元素之间的间接通信问题
【发布时间】:2020-08-19 17:39:26
【问题描述】:

我在 React Native 中的间接通信有问题。

我有一个父组件,每个类一个组件。我有一个子组件,它是一个功能组件。

家长:

constructor(props) {
  super(props);

  this.state = {
    search: '',
  };
 }

getInfoSearch(userSearch) {
 this.setState({
   search: userSearch
 })
}

render(){
  return(
   <SearchHeader placeholder={'Buscar procedimento'} getValueUserSearch={this.getInfoSearch}/>
  )
}

孩子:

import React, {useState} from 'react';
import {View, TextInput} from 'react-native';

const SearchHeader = props => {
  const [search, setSearch] = useState('');

  const {placeholder, getValueUserSearch} = props;

  const handleSearch = (search) => {
    console.log(this);
    setSearch(search);
    getValueUserSearch(search);
  };

  return (
    <View>
      <TextInput placeholder={placeholder || 'Buscar'} onChangeText={handleSearch}/>
    </View>
  );
};

export default SearchHeader;

但是当我在 InputText 中输入文本时,会发生错误。声明:

"我无法应用 undefined 的 setState 函数"

你知道我该如何解决这个问题吗?因为我想改变父元素中的“搜索”状态。

【问题讨论】:

  • getInfoSearch 使用箭头功能。否则在constructor进行绑定
  • this 内部 getInfoSearch 方法的值可能不是您所期望的。尝试在getInfoSearch 中记录this,看看它的值是多少。

标签: javascript reactjs react-native frontend dom-events


【解决方案1】:

错误可能是因为getInfoSearch 函数中的this.setState 行。

尝试使用arrow function 或在constructor 中进行显式绑定,如下所示

constructor(props) {
  ...
  this.getInfoSearch = this.getInfoSearch.bind(this);
}

(或)

getInfoSearch = (userSearch) => {
  this.setState({ search: userSearch });
}

查看here了解更多详情。

【讨论】:

    【解决方案2】:

    这是因为您没有将参数传递给handleSearch 函数,它应该是:

     onChangeText={(event) => handleSearch(event.target.value}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-19
      • 2019-03-19
      • 2016-07-19
      • 2021-03-11
      • 2013-04-30
      • 1970-01-01
      相关资源
      最近更新 更多