如何解决父子元素之间的间接通信问题
我在本机反应中进行间接通信时遇到问题。
我有一个父组件,每个类一个组件。而且我有一个子组件,它是一个功能组件。
父母:
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中键入文本时,会发生错误。说明:
“我无法应用未定义的setState函数”
您知道我该如何解决这个问题?因为我想更改父元素中的“搜索”状态。
解决方法
错误可能是由于this.setState
函数中的getInfoSearch
行引起的。
尝试使用arrow function
或在constructor
中进行显式绑定,如下所示
constructor(props) {
...
this.getInfoSearch = this.getInfoSearch.bind(this);
}
(或)
getInfoSearch = (userSearch) => {
this.setState({ search: userSearch });
}
检查here以获得更多详细信息。
,这是因为您没有将参数传递给handleSearch
函数,它应该是:
onChangeText={(event) => handleSearch(event.target.value}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。