簡體   English   中英

React TypeScript:功能組件中 UseRef 的替代方案

[英]React TypeScript: Alternatives to UseRef in functional components

是否有另一種從 dom 獲取/設置值的方法比 useRef() 便宜? 是否像文檔建議的那樣輕而易舉地使用 useRef() ?

import React, { useRef, useEffect } from 'react';

const Join: React.FC = () => {

  const fullName = useRef<HTMLInputElement>(null);
  const email = useRef<HTMLInputElement>(null);
  const password = useRef<HTMLInputElement>(null);
  const myForm = useRef<HTMLFormElement>(null);

  useEffect(() => {
    if (myForm.current) myForm.current.reset();
    if (fullName.current) fullName.current.focus();
  }, []);


  return (
    <div>
      <form ref={myForm}>
       <input type='text' ref={fullName} />
       <input type='text' ref={email} />
       <input type='text' ref={password} />
      </form>
    </div>
  )

}

當組件加載時,我想清除表單並關注 fullName 輸入

你不需要refs

我想清除表格

  • 控制您的inputs
  • 聲明一個空字符串作為初始值

const Component = () =>{
    const [state, setState] = useState({
        email : '',
        password : ''
    })

    const onChange = ({ target: { value, name } }) =>{
        setState(prev => ({
            ...prev,
            [name] : value
        }))
    } 

    const { email, password } = state
    return(
        <>
            <input value={email} onChange={onChange} id='email'/>
            <input value={password} onChange={onChange} id='password' />
        </>
    )
}

自動聚焦給定的輸入

只需為此使用autofocus

<input autofocus/>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM