React中useRef()和createRef()的使用

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;

createRef()
class Test extends Component {
  constructor(props) {
    super(props);
    this.state = { 
      myDiv:createRef()
     }
  }

  componentDidMount(){
    console.log("this.myDiv.current", this.state.myDiv.current);
    // 打印結果: this.myDiv.current <div>​ref獲取的dom元素​</div>​
  }

  render() { 
    return ( 
      <div ref={this.state.myDiv}>ref獲取的dom元素</div>
     );
  }
}
 
export default Test;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章