方法1
父组件
class App extends React.Component{
constructor(props){
super(props)
this.myChild = React.createRef();
}
click=()=>{
console.log(this.myChild.current.click())
}
render(){
return(
<div>
<Hello ref={this.myChild} />
<button onClick={this.click}>点击</button>
</div>
)
}
}
子组件
class Hello extends React.Component{
click=()=>{
alert(1)
}
render(){
return(
<h1 onClick={this.click}>hello</h1>
)
}
}
方法2
父组件
class App extends React.Component{
constructor(props){
super(props)
}
click=()=>{
console.log(this.myChild.click())
}
render(){
return(
<div>
<Hello onRef={(ref)=>this.myChild=ref} />
<button onClick={this.click}>点击</button>
</div>
)
}
}
子组件
class Hello extends React.Component{
componentDidMount(){
this.props.onRef(this)
}
click=()=>{
alert(1)
}
render(){
return(
<h1 onClick={this.click}>hello</h1>
)
}
}