类组件创建ref对象
使用 React.createRef,createRef 只做了一件事,就是创建了一个对象,对象上的 current 属性,用于保存通过 ref 获取的 DOM 元素,组件实例等。
export default class StateDemo extends React.Component {
constructor(props) {
super(props);
this.currDom = React.createRef(null);
}
componentDidMount() {
console.log(this.currDom)
}
render() {
return (
<div ref={this.currDom}>ref对象模式获取DOM元素或组件</div>
)
}
}
\
函数组件创建ref对象
const currentDom = React.useRef(null)
export default function Index(){
const currentDom = React.useRef(null)
React.useEffect(()=>{
console.log( currentDom.current ) // div
},[])
return <div ref={ currentDom } >ref对象模式获取元素或组件</div>
}
createRef() 和 useRef() 区别
ref 保存位置不相同,类组件有一个实例 instance 能够维护像 ref 这种信息,useRef 产生的 ref 对象挂到函数组件对应的 fiber 上。
类组件获取ref方式
1. ref属性是字符串
使用 this.refs获取,未来这一属性可能会被弃用。
export default class Index extends React.Component{
componentDidMount(){
console.log(this.refs)
}
render=()=> <div>
<div ref="currentDom" >字符串模式获取元素或组件</div>
<Children ref="currentComInstance" />
</div>
}
2. ref属性是函数
export default class Index extends React.Component{
currentDom = null
currentComponentInstance = null
componentDidMount(){
console.log(this.currentDom)
console.log(this.currentComponentInstance)
}
render=()=> <div>
<div ref={(node)=> this.currentDom = node } >Ref模式获取元素或组件</div>
<Children ref={(node) => this.currentComponentInstance = node } />
</div>
}
3. ref属性是ref对象
export default class Index extends React.Component{
currentDom = React.createRef(null)
currentComponentInstance = React.createRef(null)
componentDidMount(){
console.log(this.currentDom)
console.log(this.currentComponentInstance)
}
render=()=> <div>
<div ref={ this.currentDom } >Ref对象模式获取元素或组件</div>
<Children ref={ this.currentComponentInstance } />
</div>
}