【发布时间】:2021-02-11 17:51:03
【问题描述】:
在寻找避免在每次更改输入字段后呈现组件的方法时,我遇到了使用 useRef 而不是 onChange 事件进行状态更新的建议。在简单的组件中似乎还可以,但由于我是初学者,我不知道这在更复杂的应用程序中是否是一种好方法。 Shell 我继续这样还是我应该坚持 onChange 事件? 我进行了很多搜索以解决这个困境,但无法找到明确的答案。任何这方面的建议都会受到更多的欢迎。
这是它在组件中的样子:
import React, { useRef, useState } from 'react';
import axios from 'axios';
const AddData : React.FC= () => {
const initialData = {
firstValue: '',
secondValue : ''
}
const [data, setData] = useState(initialData);
const formRef = useRef<HTMLFormElement>(null);
const firstInputRef = useRef<HTMLInputElement>(null);
const secondInputRef = useRef<HTMLInputElement>(null);
const handleSetData = (e: React.MouseEvent<HTMLButtonElement, MouseEvent>) => {
if(firstInputRef.current !== null && secondInputRef.current !== null) {
setData({
...data,
firstValue: firstInputRef.current.value,
secondValue: secondInputRef.current.value
})
}
}
const handleFormSubmit = async (e:React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const {firstValue, secondValue} = data;
if(firstValue !== '' && secondValue !== '') {
await axios.post('url', {
...data
}).then((response) => { });
}
}
return(
<>
<form ref={formRef} onSubmit={handleFormSubmit}>
<input type='text' ref={firstInputRef} />
<input type='text' ref={secondInputRef} />
<button onClick={handleSetData}> Submit Form </button>
</form >
</>
);
}
export default AddData;
【问题讨论】:
标签: reactjs state onchange use-ref