在React中的子父通信实现方式是,父组件将自己的某个方法传递给子组件,在方法里可以做任意操作,比如可以更改状态,子组件通过this.props接收到父组件的方法后调用。
App.js
import React, { Component } from "react";
// 定义父组件App
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
count: 0,
};
}
render() {
return (
<div>
<h2>当前计数:{this.state.count}</h2>
<button onClick={(e) => this.incerment()}>+</button>
<CountButton
increment={this.incerment.bind(this)}
></CountButton>
</div>
);
}
//定义修改count的方法
incerment(value) {
this.setState({
count: this.state.count + value,
});
}
}
// 定义子组件
class CountButton extends Component {
constructor(props) {
super(props);
this.state = {
value: 10,
};
}
render() {
const { increment } = this.props;
return <button onClick={increment(this.state.value)}>+</button>;
}
}