import React from 'react'
export default class RefDemo extends React.Component {
constructor() {
super()
this.objRef = React.createRef()
}
componentDidMount() {
setTimeout(() => {
this.refs.stringRef.textContent = 'string ref got'
this.methodRef.textContent = 'method ref got'
this.objRef.current.textContent = 'obj ref got'
}, 2000)
}
render() {
return <div>
<p ref="stringRef">span1</p>//第三种
<p ref={ele => (this.methodRef = ele)}>span2</p>//第二种
<p ref={this.objRef}>span3</p>
</div>
}
}
import React from 'react'
const TargetFunction = React.forwardRef((props,ref)=>(
<input type="text" ref={ref}/>
))
export default class FrodWordRefDemo extends React.Component {
constructor() {
super()
this.ref = React.createRef()
}
componentDidMount() {
this.ref.current.value = 'ref get input'
}
render() {
return <TargetFunction ref={this.ref}>
</TargetFunction>
}
}