React中操纵和监听或同步Form表单中的数据(如Input中的值)两种方法

获取Form表单中的数据的两种方法(以Input为例)

1.通过formRef.current.getFieldsValue()获取Form表单中所有数据

const formRef = createRef<any>();
//1.获取 表单中所有数据的方法
let rtkobj =formRef.current.getFieldsValue();
  //取出某条数据
 rtkobj.landName
//2.重置 表单中所有数据
formRef.current.resetFields();
//3.设置 表单中某个组件的值(formRef.current.getFieldsValue()中一定要有这个属性名)
    //直接
formRef.current.setFieldsValue({
    
     landName: '新值' });
    //间接(已知inputId="landName"时)
formRef.current.setFieldsValue({
    
     [inputId]: '新值' });

//组件
<Form className="rtk-form" ref={
    
    formRef}>
     <Form.Item
        label="地块名称"
        name="landName"
        colon={
    
    false}
        labelAlign="right"
        labelCol={
    
    {
    
     span: 4 }}
        rules={
    
    [{
    
     required: true, message: '请输入地块名称' }]}>
        <Input style={
    
    {
    
     width: '93%', height: 40 }} placeholder="请输入地块名称" />
     </Form.Item>
</Form>

2.通过Form.useForm()获取Form表单中所有数据,用法与上面一样,中间不用加current

const [formRef] = Form.useForm();
//1.获取 表单中所有数据的方法
let rtkobj =formRef.getFieldsValue();
//以此类推
<Form className="form" form={
    
    formRef}>
     <Form.Item
        label="地块名称"
        name="landName"
        colon={
    
    false}
        labelAlign="right"
        labelCol={
    
    {
    
     span: 4 }}
        rules={
    
    [{
    
     required: true, message: '请输入地块名称' }]}>
        <Input style={
    
    {
    
     width: '93%', height: 40 }} placeholder="请输入地块名称" />
     </Form.Item>
</Form>

注意:以上两种方法分情况使用,只要能拿到数据用那种都可以。

监听或同步Form表单中的数据(如Input中的值)两种方法

1.利用useState和onChange事件传统渲染,

const [keyWord, setKeyWord] = useState('');

   <Input
     value={
    
    keyWord}
      onChange={
    
    (e) => setKeyWord(e.target.value)}
      size="large"
      style={
    
    {
    
     width: 240, marginRight: 24 }}
      placeholder="请输入机具名称"
    />

2.利用formRef.current.setFieldsValue()方法,设置的新值会同步到组件上显示

//3.设置 表单中某个组件的值(formRef.current.getFieldsValue()中一定要有这个属性名)
    //直接
formRef.current.setFieldsValue({
    
     landName: '新值' });
    //间接(已知inputId="landName"时)
formRef.current.setFieldsValue({
    
     [inputId]: '新值' });

//组件
<Form className="rtk-form" ref={
    
    formRef}>
     <Form.Item
        label="地块名称"
        name="landName"
        colon={
    
    false}
        labelAlign="right"
        labelCol={
    
    {
    
     span: 4 }}
        rules={
    
    [{
    
     required: true, message: '请输入地块名称' }]}>
        <Input style={
    
    {
    
     width: '93%', height: 40 }} placeholder="请输入地块名称" />
     </Form.Item>
</Form>

注意:
在业务处理中,有时Input框多次改变输入值后可能通过let rtkobj =formRef.current.getFieldsValue()确实能拿到数据,但是在业务方法中没有及时获取打印,而不方便进行下一步操作,此时可以通过其onblur(e)或onChange(e)方法中的参数e.target.value快速拿到具体输入值进行操作。

猜你喜欢

转载自blog.csdn.net/qq_37967853/article/details/128969841