在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值。
这两种方式都可以获取表单数据,具体使用哪种方式要根据实际情况和个人喜好来决定。