欢迎您来到,李雷博客 | PHP博客        登录  |  注册

react中满足对自己的组件使用setFieldsValue

更新:2023-03-12 09:16:50
人气:157
来源:互联网转载
A+

这篇文章主要介绍“react中满足对自己的组件使用setFieldsValue”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“react中满足对自己的组件使用setFieldsValue”文章能帮助大家解决问题。

    react对自己的组件使用setFieldsValue

    setFieldsValue的用法

    setFieldsValue是antd form的一个api,其作用是对指定的已使用from包裹的表单进行value设置。那么所以它的功能也很简单,那就是给指定的input设置value。

    如下所示:

    import React from "react";
    import { Form, Input } from 'antd';
    
    class TestForm extends React.Component {
      componentDidMount(){
        const { setFieldsValue } = this.props.form;
        // 这里就能实现指定表单设置value
        setTimeout(()=>{
            setFieldsValue({"username": "Tom"})
        },5000)
      }
      render() {
        const { getFieldDecorator } = this.props.form;
        return (
          <Form >
            <Form.Item>
              {getFieldDecorator('username', {})(<Input />)}
            </Form.Item>
          </Form>
        );
      }
    }
    
    export default Form.create()(TestForm)

    问题

    那么假如把

    {getFieldDecorator('username', {})(<Input />)}

    换成

    {getFieldDecorator('username', {})(<TestInput />)}

    setFieldsValue 设置的value去哪了?相信聪明的你一眼就看透了,自然是在TestInput上面。假如TestInput是我们自定义的组件,那么我们则可以在props中找value这个属性,那么假如我们的Input是自定义的input组件,我们可以这么写

    import React from "react";
    import { Input } from 'antd';
    
    class TestInput extends React.Component {
    
        state = {
            value: ""
        }
        
        componentWillReceiveProps(nextProps){
            if(nextProps.value){
                this.setState({
                    value: nextProps.value
                })
            }
        }
        
        render() {
            return (
              <div >
                  <Input value={this.state.value}/>
              </div>
            );
          }
    }
    
    export default TestInput

    这样,我们就能使用setFieldsValue设置自定义的组件了

    使用Hooks使用setFieldsValue设置初始值无效

    react中满足对自己的组件使用setFieldsValue

    错误:

      useEffect(() => {
        if (formConfigListValues.length === 0) {
          form.resetFields();
          if (statusId) {
            form.setFieldsValue({flowStatus: 1});
          }
        }
      }, [formConfigListValues, statusId]);

    因为formConfigListValues在每次操作完表单时候要走一遍,但是导致了,审批状态一直不会变(也就是操作审核状态失效);

    正确:

      useEffect(() => {
        if (formConfigListValues.length === 0) {
          form.resetFields();
        }
      }, [formConfigListValues]);
      
      useEffect(() => {
          if (statusId) {
            form.setFieldsValue({flowStatus: 1});
          }
      }, [statusId]);

    在hooks中使用setFieldsValue,还要注意写代码的顺序和层级结构(如:新加的setFieldsValue到底放在里边还是外边,放到外边的话是否要注意,要放在resetFields所在useEffect的下边)。

    推荐的文章
    网站地图
    会员服务
    关于我们
    QQ:858353007
     
    广告服务
    加我微信
    移动端访问
     
     
    Copyright © 2014- 2023 www.mdaima.com All Rights Reserved.
    李雷博客,专注PHP经验、PHP教程及PHP源代码开源下载分享的PHP博客!   ICP备案号:京ICP备10202169号-4