<
>

react中如何对自己的组件使用setFieldsValue

2023-03-11 15:05:27 来源:易采站长站 作者:

目录react对自己的组件使用setFieldsValuesetFieldsValue的用法问题使用Hooks使用setFieldsValue设置初始值无效总结react对自己的组件使用setFiel...

目录
react对自己的组件使用setFieldsValue
setFieldsValue的用法
问题
使用Hooks使用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.setjsFieldsValue({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的下边)。

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

暂时禁止评论

微信扫一扫

易采站长站微信账号