在React中獲取表單數據有幾種方式:
import React, { useState } from 'react';
function Form() {
const [formData, setFormData] = useState({
name: '',
email: '',
});
const handleChange = (e) => {
setFormData({ ...formData, [e.target.name]: e.target.value });
};
const handleSubmit = (e) => {
e.preventDefault();
console.log(formData);
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
name="name"
value={formData.name}
onChange={handleChange}
/>
<input
type="email"
name="email"
value={formData.email}
onChange={handleChange}
/>
<button type="submit">Submit</button>
</form>
);
}
export default Form;
import React, { useRef } from 'react';
function Form() {
const nameRef = useRef();
const emailRef = useRef();
const handleSubmit = (e) => {
e.preventDefault();
console.log(nameRef.current.value, emailRef.current.value);
};
return (
<form onSubmit={handleSubmit}>
<input type="text" ref={nameRef} />
<input type="email" ref={emailRef} />
<button type="submit">Submit</button>
</form>
);
}
export default Form;
上面的例子中,nameRef和emailRef分別引用了input元素,調用nameRef.current.value和emailRef.current.value就可以獲取到對應的input值。
這兩種方式都可以獲取表單數據,具體使用哪種方式要根據實際情況和個人喜好來決定。