通过父组件获取子组件的实例,调用子组件的方法并在方法中传参,子组件在自己的这个方法里将参数赋值给状态,这种一般用做手动传参,
比如子组件是一个对话框,父组件点击某个方法要对话框显示,因此就可以利用ref获取子组件实例传参,并调用子组件实例的方法修改子组件的状态,来实现控制对话框的显示,
import React, { Children, Component } from 'react';
// import PT from 'prop-types'
class Hellow extends Component {
constructor(props){
super(props);
this.state={
isshow:false
}
}
// ========== 这个是子组件
dian(index){
console.log('子组件',index)
this.setState({isshow:index})
}
// =========
render() {
console.log('zi reder')
return (
<div style={ {visibility:this.state.isshow ? 'visible':'hidden'} } >
<h2>假如我是个提示框</h2>
<button onClick={()=>{this.dian(false)}}>关闭对话框</button>
</div>
);
}
}
export default Hellow;
// ======== 父组件
<Hellow ref="hellow"></Hellow>
// 父组件的显示对话框按钮事件
handle(){
console.log(this.refs.hellow.dian(true))
}