将值传递给父组件 undefined
2019-02-26
709
我尝试将值从 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} />
)
}
运行它时出现未定义警报。如何正确地将值从子组件传递到父组件?
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>
Tholle
2019-02-26