- 父组件将自己的状态传递给子组件,子组件当做属性来接收,当父组件更改自己状态的时候,子组件接收到的属性就会发生改变
- 父组件利用ref对子组件做标记,通过调用子组件的方法以更改子组件的状态,也可以调用子组件的方法
父组件将自己的某个方法传递给子组件,在方法里可以做任意操作,比如可以更改状态,子组件通过this.props接收到父组件的方法后调用。
在父组中定义ref引用
import React, { Component, createRef } from 'react'
import Child1 from './components/Child1'
import Sub from './components/Sub'
// 只有在类组件中才有生命周期
export default class App extends Component {
constructor(props) {
super(props);
// 定义一个成员属性用于ref引用的变量
this.child = createRef()
}
state = {
username: 'admin',
sex: '男',
count: 1
}
render() {
return (
<div>
<Child1 ref={this.child} setCount={this.setCount.bind(this)} />
<hr />
<button onClick={this.fn.bind(this)}>修改一下子组件中的内容</button>
<hr />
<h3>{this.state.count}</h3>
<Sub />
</div>
)
}
fn() {
// 通过ref得到子组件的实例对象
const child = this.child.current
// 调用子组件中的方法
child.setTitle()
// console.log(child.state.title);
}
setCount() {
this.setState(prevState => {
return { count: ++prevState.count };
});
}
}
子组件定义好数据源和修改数据源方法
import React, { Component } from 'react'
export default class Child1 extends Component {
state = {
title: '我是一个子组件'
}
componentDidMount(){
setTimeout(() => {
this.props.setCount()
}, 3000);
}
render() {
return (
<div>
{this.state.title}
</div>
)
}
setTitle() {
this.setState({
title: 'aaabbccc'
})
}
}