我正在尝试通过props将值从子组件传递到父组件,并在其中带有函数,但会引发错误undefined is not a function(evaluating(this.setstate({search: val}))
,请问我在做什么错
class Child extends React.Component {
do() {
this.props.value("books");
}
componentDidMount() {
this.do();
}
render() {
return <Text>yams</Text>;
}
}
class Parent extends React.Component {
constructor(props) {
super(props);
this.state = {
search: ""
};
}
handleChange = e => {
this.props.onUpdate(e.target.value);
this.setState({ search: e.target.value });
};
con(val) {
this.setState({ search: val });
}
render() {
return (
<View>
<Child value={this.con} />
<Text>{this.state.search}</Text>{" "}
</View>
);
}
}
答案 0 :(得分:3)
您需要.bind
的功能才能使用this
。在您的构造函数中执行此操作,或改为使用箭头函数。
constructor(props){
super(props);
this.state= {
search: ''
}
this.con = this.con.bind(this);
}
或
con = val =>
this.setState({search: val});
答案 1 :(得分:1)
将con
函数定义为粗箭头函数:
con = (val) => {
this.setState({search: val});
}
这会将this
绑定到父类上下文