setFieldsValue设置自己值使输入框受控。

antd中form表单的setFieldsValue只能设置其他域的值,不能控制自己表单域的值,另外我希想把redux中传过来的props绑定到form,使props改变表单值实时改变。不能使用value,应该如何处理。

class App extends React.Component {
 state={
     a:123
 }
  handleSubmit = (e) => {
 e.preventDefault();
 this.props.form.validateFields((err, values) => {
   if (!err) {
     console.log('Received values of form: ', values);
   }
 });
  }
  handleSelectChange = (e) => {
 console.log(e.target.value)
 this.props.form.setFieldsValue({
   note: '123',
   gender:'1'
 });
  }
  render() {
 const { getFieldDecorator } = this.props.form;
 const a=/^\d{1,6}$/
 return (
   <Form onSubmit={this.handleSubmit}>
     <FormItem
       label="Note"
       labelCol={{ span: 4 }}
       wrapperCol={{ span: 8 }}
     >
       {getFieldDecorator('note', {
         rules: [{ required: true, message: 'Please input your note!' },{pattern:a,message:'请输入1-6位'}],
       })(
         <Input onChange={this.handleSelectChange.bind(this)}/>
       )}
     </FormItem>
     <FormItem
       label="Gender"
       labelCol={{ span: 4 }}
       wrapperCol={{ span: 8 }}
     >
       {getFieldDecorator('gender', {
         rules: [{ required: true, message: 'Please select your gender!' }],
       })(
         <Select
           placeholder="Select a option and change input text above"
           onChange={this.handleSelectChange}
         >
           <Option value="1">male</Option>
           <Option value="2">female</Option>
         </Select>
       )}
     </FormItem>
     <FormItem
       wrapperCol={{ span: 8, offset: 4 }}
     >
       <Button type="primary" htmlType="submit">
         Submit
       </Button>
     </FormItem>
   </Form>
 );
  }
}

const WrappedApp = Form.create()(App);

这是第一个输入框实时输入,我不能对表单进行控制。

阅读 21.1k
1 个回答

做类似功能也发现了同样的问题,然后发现了大佬提供的解决方法,里面还阐述了下原理为什么setFieldsValue不可以。反正没太看懂但是按着说的方法解决了就是了,地址:http://ju.outofmemory.cn/entr...
参照着用的解决方法就是用antd官方提供的options.normalize

// 这里实现的是数值大于60就自动加"/"
function createField1({
    key,
    formItem,
    required,
    message,
    validator,
    normalize
  }) {
    const rules = [
      {
        required: required || false,
        message,
        validator
      }
    ];
    let initialValue = item[key] ? item[key] + "" : "";
    return getFieldDecorator(key, { normalize, rules, initialValue })(formItem);
  }

<FormItem label="血压:" key="pressure">
      {createField1({
        key: "bloodPressure",
        formItem: (
          <Select
            mode="combobox"
            size="large"
            defaultActiveFirstOption={false}
            showArrow={false}
            filterOption={false}
          >
            {option}
          </Select>
        ),
        normalize: (e) => {
          if (!isNaN(e) && e > 60) {
            return e + "/";
          }
          return e;
        }
      })}
    </FormItem>
推荐问题
宣传栏