一、createRef()
class Test extends Component {
constructor(props) {
super(props);
this.state = {
myDiv:createRef()
}
}
componentDidMount(){
console.log("this.myDiv.current", this.state.myDiv.current);
}
render() {
return (
<div ref={this.state.myDiv}>ref获取的dom元素</div>
);
}
}
export default Test;
二、useRef()
import React, {useState, useRef, createRef, useEffect } from 'react';
const Test = ()=>{
const [ index, setIndex ] = useState(1);
const createRefDiv = createRef();
const useRefDiv = useRef();
if(!createRefDiv.current){
createRefDiv.current = index;
}
if(!useRefDiv.current){
useRefDiv.current = index;
}
return(
<>
<div>createRefDiv.current: {createRefDiv.current}</div>
<div>useRefDiv.current: {useRefDiv.current}</div>
<div>
<button onClick={()=>setIndex(index+1)}>改变Index</button>
</div>
</>
)
}
export default Test;