createRef
createRef γ―δ»»ζοΏ½?ε€γδΏζγ§γγ ref γͺγγΈγ§γ―γγδ½ζγγΎγγ
class MyInput extends Component {
inputRef = createRef();
// ...
}γͺγγ‘γ¬γ³γΉ
createRef()
createRef γεΌγ³εΊγγ¦γγ―γ©γΉγ³γ³γγΌγγ³γε
γ§ ref γοΏ½?οΏ½θ¨γγΎγγ
import { createRef, Component } from 'react';
class MyComponent extends Component {
intervalRef = createRef();
inputRef = createRef();
// ...εΌζ°
createRef γ―εΌζ°γεγγΎγγγ
θΏγε€
createRef γ―εδΈοΏ½?γγγγγ£γζγ€γͺγγΈγ§γ―γγθΏγγΎγγ
current:nullγ«εζεγγγ¦γγΎγγεΎγ§δ»οΏ½?ε€γ«γ»γγγγγγ¨γγ§γγΎγγJSX γγΌγοΏ½?refε±ζ§γ¨γγ¦ React γ« ref γͺγγΈγ§γ―γγζΈ‘γγ¨γReact γ―γοΏ½?currentγγγγγ£γι©εγ«γ»γγγγΎγγ
注ζηΉ
createRefγ―εΈΈγ«η°γͺγγͺγγΈγ§γ―γγθΏγγΎγγγγγ―θͺεγ§{ current: null }γζΈγοΏ½?γ¨εηγ§γγ- ι’ζ°γ³γ³γγΌγγ³γγ§γ―γεγγͺγγΈγ§γ―γγεΈΈγ«θΏγ
useRefγ代γγγ«δ½Ώη¨γγγγ¨γγε§γγγΎγγ const ref = useRef()γ―const [ref, _] = useState(() => createRef(null))γ¨εηγ§γγ
δ½Ώη¨ζ³
γ―γ©γΉγ³γ³γγΌγγ³γγ§ ref γοΏ½?οΏ½θ¨γγ
γ―γ©γΉγ³γ³γγΌγγ³γε
γ§ ref γοΏ½?οΏ½θ¨γγγ«γ―γcreateRef γεΌγ³εΊγγγοΏ½?η΅ζγγ―γ©γΉγγ£γΌγ«γγ«ε²γε½γ¦γΎγγ
import { Component, createRef } from 'react';
class Form extends Component {
inputRef = createRef();
// ...
}γγγ§ JSX οΏ½? <input> γ« ref={this.inputRef} γζΈ‘γγ¨γReact γ― this.inputRef.current γ input οΏ½? DOM γγΌγγ«γ»γγγγΎγγδΎγγ°δ»₯δΈοΏ½?γγγ«γγ¦γinput γγγ©γΌγ«γΉγγγγΏγ³γδ½γγγ¨γγ§γγΎγγ
import { Component, createRef } from 'react'; export default class Form extends Component { inputRef = createRef(); handleClick = () => { this.inputRef.current.focus(); } render() { return ( <> <input ref={this.inputRef} /> <button onClick={this.handleClick}> Focus the input </button> </> ); } }
代ζΏζοΏ½?οΏ½
createRef γδ½Ώγ£γγ―γ©γΉγγ useRef γδ½Ώγ£γι’ζ°γΈοΏ½?η§»θ‘
ζ°γγγ³γΌγγ§γ―γ―γ©γΉγ³γ³γγΌγγ³γοΏ½?代γγγ«ι’ζ°γ³γ³γγΌγγ³γοΏ½?δ½Ώη¨γζ¨ε₯¨γγΎγγδ»₯δΈγ«γcreateRef γδ½Ώη¨γγ¦γγζ’εοΏ½?γ―γ©γΉγ³γ³γγΌγγ³γγγγε ΄εοΏ½?η§»θ‘ζΉζ³γη€ΊγγΎγγγγ‘γγε
οΏ½?γ³γΌγγ§γγ
import { Component, createRef } from 'react'; export default class Form extends Component { inputRef = createRef(); handleClick = () => { this.inputRef.current.focus(); } render() { return ( <> <input ref={this.inputRef} /> <button onClick={this.handleClick}> Focus the input </button> </> ); } }
γοΏ½?γ³γ³γγΌγγ³γγγ―γ©γΉγγι’ζ°γ«η§»θ‘γγε ΄εγcreateRef οΏ½?εΌγ³εΊγγ useRef οΏ½?εΌγ³εΊγγ«οΏ½?γζγγΎγγ
import { useRef } from 'react'; export default function Form() { const inputRef = useRef(null); function handleClick() { inputRef.current.focus(); } return ( <> <input ref={inputRef} /> <button onClick={handleClick}> Focus the input </button> </> ); }