import React from 'react'
export default class RefDemo extends React.Component {
constructor() {
super()
this.objRef = React.createRef()
// { current: null }
}
componentDidMount() {
setTimeout(() => {
this.refs.stringRef.textContent = 'string ref got'//字符串
this.methodRef.textContent = 'method ref got'//回调函数
this.objRef.current.textContent = 'obj ref got'//React.createRef()
console.log(this.objRef.current)//<p>obj ref got</p>
console.log(this.methodRef)//<p>method ref got</p>
}, 1000)
}
render() {
return (
<>
<p ref="stringRef">span1</p>
<p ref={ele => (this.methodRef = ele)}>span3</p>
<p ref={this.objRef}>span3</p>
</>
)
}
}
关于forwardRef:
想要将ref传值给子组件,但是props没有ref(源码之ReactElement有提),所以需要通过React.forwardRef传递ref,
import React from 'react'
const TargetComponent = React.forwardRef((props, ref) => (
<input type="text" ref={ref} />
))
export default class Comp extends React.Component {
constructor() {
super()
this.ref = React.createRef()
}
componentDidMount() {
this.ref.current.value = 'ref get input'
}
render() {
return <TargetComponent ref={this.ref} />
}
}