简体   繁体   English

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

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

Is there another way of getting/setting the values from the dom that is less expensive than useRef()?是否有另一种从 dom 获取/设置值的方法比 useRef() 便宜? Is useRef() to be used lightly as the docs suggest?是否像文档建议的那样轻而易举地使用 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>
  )

}

When the component loads I want to clear the form and focus the fullName input当组件加载时,我想清除表单并关注 fullName 输入

You don't need refs for that你不需要refs

I want to clear the form我想清除表格

  • Make your inputs controlled控制您的inputs
  • Declare an empty string as initial value声明一个空字符串作为初始值

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' />
        </>
    )
}

Automatically focus a given input自动聚焦给定的输入

Just use autofocus for that只需为此使用autofocus

<input autofocus/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM