import React, { Component } from 'react'
class ChildNode extends Component {
constructor(props){
super(props)
this.state={
count:1
}
}
addCount=()=>{
let newCount = this.state.count+1;
this.setState({
count:newCount
})
}
render() {
return (
<div>
<p>子组件</p>
<p>{this.state.count}</p>
<button onClick={this.addCount}>点我+1</button>
</div>
)
}
}
class ParentNode extends Component {
state={
num:1
}
childRef = React.createRef();
logRef=()=>{
// console.log(this.childRef.current)
// this.childRef.current.addCount()
// 使用函数式绑定ref就得使用下面这种获取方法
console.log(this.childRef)
this.childRef.addCount()
}
render() {
return (
<div>
<h3>父组件</h3>
<button onClick={this.logRef}>打印且调用子组件的方法</button>
{/* 简单的使用ref获取dom */}
{/* <ChildNode ref={this.childRef}/> */}
{/* 使用函数式绑定ref*/}
<ChildNode ref={el=>this.childRef=el}/>
</div>
)
}
}
export default ParentNode
版权声明:本文为Arbort_原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。