【问题标题】:Antd Select not setting initial valueAntd Select不设置初始值
【发布时间】:2021-08-04 08:32:55
【问题描述】:

我在antd Select中设置初始值有问题

const options=[{name:'john',id:1},{name:'jack',id:2},{name:'jill',id:3}]
   <Form initialValues={{user:3}}>
    <Form.Item name="user" label="Select user">
        <Select value="3">
        {options.map((user,index)=><Option key={index} value={user.id}>{user.name}</Option>)}
        </Select>
    </Form.Item>
   </Form>

它没有选择初始值。任何想法。这是实现它的正确方法吗,请帮助

【问题讨论】:

  • 能否请您添加工作演示以便我们更好地查看?谢谢!
  • 我刚刚发现 API 响应 ID 有问题感谢问题已修复

标签: reactjs forms antd


【解决方案1】:

下面是Antd Form中Select Component的简单demo 我想知道这些选项是来自商店还是其他组件?因此,一旦安装表单,表单就不会获得初始值。如果它来自其他来源,您需要订阅初始值,如果它发生更改以重置 antd 表单,如

import React from 'react';
import ReactDOM from 'react-dom';
import 'antd/dist/antd.css';
import './index.css';
import { Form, Input, Button, Checkbox, Select } from 'antd';
const layout = {
  labelCol: {
    span: 8,
  },
  wrapperCol: {
    span: 16,
  },
};
const tailLayout = {
  wrapperCol: {
    offset: 8,
    span: 16,
  },
};
// useEffect(() => {
  //   form.resetFields()
  //   form.setFieldsValue({
  //     productName: productName
  //   })
  // }, [initialValues]);
const userNameOptions = [{name:'john',id:1},{name:'jack',id:2},{name:'jill',id:3}]
const Demo = () => {
  const onFinish = (values) => {
    console.log('Success:', values);
  };

  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };

  return (
    <Form
      {...layout}
      name="basic"
      initialValues={{
        remember: true,
        username: 3
      }}
      onFinish={onFinish}
      onFinishFailed={onFinishFailed}
    >
      <Form.Item
        label="Username"
        name="username"
        rules={[
          {
            required: true,
            message: 'Please input your username!',
          },
        ]}
      >
        <Select value='3'>
          {userNameOptions.map((item, index) => (
            <Select.Option key={index} value={item.id}>
              {item.name}
            </Select.Option>
          ))}
        </Select>
      </Form.Item>

      <Form.Item
        label="Password"
        name="password"
        rules={[
          {
            required: true,
            message: 'Please input your password!',
          },
        ]}
      >
        <Input.Password />
      </Form.Item>

      <Form.Item {...tailLayout} name="remember" valuePropName="checked">
        <Checkbox>Remember me</Checkbox>
      </Form.Item>

      <Form.Item {...tailLayout}>
        <Button type="primary" htmlType="submit">
          Submit
        </Button>
      </Form.Item>
    </Form>
  );
};

ReactDOM.render(<Demo />, document.getElementById('container'));

【讨论】:

    猜你喜欢
    • 2020-11-21
    • 2021-05-25
    • 2018-12-25
    • 2020-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-15
    相关资源
    最近更新 更多