我不知道我哪里做错了。我无法将数据从 child 发送到 parent 。 这里有什么问题? 我如何从子状态中获取状态并发送给父状态?
这是子组件
import React from 'react';
export class Child extends React.Component{
constructor(props) {
super(props);
this.state= {
counter2: 5
}
}
render() {
return(
<div>
<button onClick={this.props.data}>Click me</button><span>{this.state.counter2}</span>
</div>
);
}
}
export default Child;
我想更新父组件中的状态
import React from 'react';
import {Child} from './Child';
export default class Parent extends React.Component{
constructor(props){
super(props);
this.state= {
counter: 0
}
}
update(){
this.setState({
counter: this.props.state.counter2
});
}
render(){
return(
<div>
<span>{this.state.counter}</span>
<Child data={this.update.bind(this)}/>
</div>
);
}
}
但是我有一个错误: × 类型错误:无法读取未定义的属性“计数器”?
我不明白我做错了什么!
谢谢
最佳答案
实际上,您的父级props
中没有state
属性。
您不能以这种方式获取 child 的状态:
this.props.state.counter2
Props ONLY 从父组件传递给子组件(如果您不使用 Redux
或其他状态管理库)。
不过,你可以这样传递它:
父组件
import React from 'react';
import {Child} from './Child';
export default class Parent extends React.Component{
constructor(props){
super(props);
this.state= {
counter: 0
}
}
update(value){
return () => {
this.setState({
counter: value
});
}
}
render(){
return(
<div>
<span>{this.state.counter}</span>
<Child data={this.update.bind(this)}/>
</div>
);
}
}
子组件
import React from 'react';
export class Child extends React.Component{
constructor(props) {
super(props);
this.state= {
counter2: 5
}
}
render() {
return(
<div>
<button onClick={this.props.data(this.state.counter2)}>Click me</button><span>{this.state.counter2}</span>
</div>
);
}
}
export default Child;
关于reactjs - 将数据从 child 发送到 parent React,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50077235/