通过 props 将子组件的组件实例( this)当作参数,通过回调传到父组件,然后在父组件就可以拿到子组件的实例,就可以调用子组件中国的方法
父组件
import React from 'react'
import Son from './Son'
class Parents extends React.Component {
sonRef = (ref) => {
// 在这里拿到子组件的实例
this.child = ref
}
clearSonInput = () => {
this.child.clearInput()
}
render() {
return (
<div>
<Son onRef={this.sonRef} />
<button type='primary' onClick={this.clearSonInput}>
清空
</button>
</div>
)
}
}
export default Parents
子组件
// 子组件
import React from 'react'
class Son extends React.Component {
componentDidMount() {
// 在这将子组件的实例传递给父组件this.props.onRef()方法
this.props.onRef(this)
}
state = {
info: 'son',
}
handleChange = (e) => {
this.setState({
info: e.target.value,
})
}
clearInput = () => {
this.setState({
info: '',
})
}
render() {
return (
<div>
<div>{this.state.info}</div>
<input type='text' onChange={this.handleChange} />
</div>
)
}
}
export default Son