使用 React 钩子处理输入 [英] Handle an input with React hooks

查看:46
本文介绍了使用 React 钩子处理输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现有几种方法可以使用钩子处理用户的文本输入.用钩子处理输入的更可取或正确的方法是什么?你会用哪个?

I found that there are several ways to handle user's text input with hooks. What is more preferable or proper way to handle an input with hooks? Which would you use?

1) 处理输入的最简单的钩子,但是你有更多的字段,你必须编写更多重复的代码.

1) The simplest hook to handle input, but more fields you have, more repetitive code you have to write.

const [username, setUsername] = useState('');
const [password, setPassword] = useState('');

事件:

onChange={event => setPassword(event.target.value)}
onChange={event => setUsername(event.target.value)}

2) 类似于上面的例子,但使用动态键名

2) Similar to above example, but with dynamic key name

const [inputValues, setInputValues] = useState({
  username: '', password: ''
});

const handleOnChange = event => {
  const { name, value } = event.target;
  setInputValues({ ...inputValues, [name]: value });
};

事件:

onChange={handleOnChange}

3) useState 的替代方案,正如 ReactJS 文档中所说,useReducer 通常比 useState 更可取.

3) An alternative to useState, and as said on ReactJS docs, useReducer is usually preferable to useState.

const [inputValues, setInputValues] = useReducer(
  (state, newState) => ({ ...state, ...newState }),
  {username: '', password: ''}
);

const handleOnChange = event => {
  const { name, value } = event.target;
  setInputValues({ [name]: value });
};

事件:

onChange={handleOnChange}

4) useCallback 将返回一个记忆化的回调版本,该版本仅在依赖项之一发生更改时才会更改.

4) useCallback will return a memoized version of the callback that only changes if one of the dependencies has changed.

const [inputValues, setInputValues] = useState({ 
  username: '', password: '' 
});

const handleOnChange = useCallback(event => {
  const { name, value } = event.target;
  setInputValues({ ...inputValues, [name]: value });
});

事件:

onChange={handleOnChange}

推荐答案

如何编写一个可重用的函数来返回输入值......以及 本身:

How about writing a reusable function that returns the input value ... and the <input> itself:

 function useInput({ type /*...*/ }) {
   const [value, setValue] = useState("");
   const input = <input value={value} onChange={e => setValue(e.target.value)} type={type} />;
   return [value, input];
 }

然后可以用作:

 const [username, userInput] = useInput({ type: "text" });
 const [password, passwordInput] = useInput({ type: "text" });

 return <>
   {userInput} -> {username} <br />
   {passwordInput} -> {password}
 </>;

这篇关于使用 React 钩子处理输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆