react如何获取vaule值
获取表单元素的值
在React中获取表单元素的值,可以通过onChange事件和useState钩子实现。创建一个状态变量来存储输入值,通过事件对象更新状态。
import React, { useState } from 'react';
function FormExample() {
const [inputValue, setInputValue] = useState('');
const handleChange = (e) => {
setInputValue(e.target.value);
};
return (
<input
type="text"
value={inputValue}
onChange={handleChange}
/>
);
}
使用ref获取DOM节点值
通过useRef钩子直接访问DOM节点,适用于需要非受控组件或直接操作DOM的场景。注意这种方式不会触发React的重新渲染。

import React, { useRef } from 'react';
function RefExample() {
const inputRef = useRef(null);
const handleClick = () => {
alert(inputRef.current.value);
};
return (
<>
<input ref={inputRef} type="text" />
<button onClick={handleClick}>Get Value</button>
</>
);
}
表单提交时获取值
在表单提交事件中,可以通过事件对象或状态变量获取所有表单字段的值。推荐使用受控组件方式管理表单数据。

function SubmitForm() {
const [formData, setFormData] = useState({ username: '', password: '' });
const handleSubmit = (e) => {
e.preventDefault();
console.log('Submitted values:', formData);
};
const handleInputChange = (e) => {
setFormData({
...formData,
[e.target.name]: e.target.value
});
};
return (
<form onSubmit={handleSubmit}>
<input
name="username"
value={formData.username}
onChange={handleInputChange}
/>
<input
name="password"
type="password"
value={formData.password}
onChange={handleInputChange}
/>
<button type="submit">Submit</button>
</form>
);
}
获取自定义组件的值
当需要从子组件获取值时,可以通过回调函数将值传递给父组件。这种方式适用于封装了表单逻辑的复合组件。
function ParentComponent() {
const handleChildValue = (value) => {
console.log('Value from child:', value);
};
return <ChildComponent onValueChange={handleChildValue} />;
}
function ChildComponent({ onValueChange }) {
const [value, setValue] = useState('');
const handleChange = (e) => {
const newValue = e.target.value;
setValue(newValue);
onValueChange(newValue);
};
return <input value={value} onChange={handleChange} />;
}
使用Formik库管理表单
对于复杂表单场景,Formik库提供了完整的解决方案,包括值获取、验证和提交处理。这种方式减少了样板代码。
import { Formik, Field, Form } from 'formik';
function FormikExample() {
return (
<Formik
initialValues={{ email: '' }}
onSubmit={(values) => {
console.log(values.email);
}}
>
<Form>
<Field name="email" type="email" />
<button type="submit">Submit</button>
</Form>
</Formik>
);
}






