我正在尝试将值从childComponent传递到父组件,但没有成功。
childComponent.js
this.state{(
val: 10
)}
handelClick(){
let val = this.state.val
this.props.useVal(val)
}
render(){
return(
<a onClick={() =>this.handelClick()}> click here</a>
)
}
parentComponent.js
this.state = {
parentVal : ''
}
useVal(val){
alert(val)
this.setState({parentVal: val})
}
render(){
return(
<childComponent useVal={() => this.useVal} />
)
}
我在运行时收到未定义的警报。如何正确地将值从子组件传递到父组件?
答案 0 :(得分:1)
您必须传递传递给useVal
prop函数的参数。
<ChildComponent useVal={val => this.useVal(val)} />
或者,您可以将useVal
方法绑定到构造函数中的this
或将其绑定到类字段箭头函数中,从而不必在render方法中创建新函数。
class ParentComponent extends React.Component {
state = {
parentVal: ""
};
useVal = (val) => {
alert(val);
this.setState({ parentVal: val });
}
render() {
return <ChildComponent useVal={this.useVal} />;
}
}
class ParentComponent extends React.Component {
state = {
parentVal: ""
};
useVal = (val) => {
alert(val);
this.setState({ parentVal: val });
}
render() {
return <ChildComponent useVal={this.useVal} />;
}
}
class ChildComponent extends React.Component {
state = {
val: 10
};
handelClick = () => {
let val = this.state.val;
this.props.useVal(val);
}
render() {
return <a onClick={this.handelClick}>click here</a>;
}
}
ReactDOM.render(<ParentComponent />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>