antd Form.Item 只接受一个孩子

问题描述 投票:0回答:3

我创建了一个小小提琴来说明这个问题:https://stackblitz.com/edit/react-avejvc-mmhqda?file=index.js

此表格有效:

      <Form initialValues={{ surname: 'Mouse'}}>
        <Form.Item name="surname">
          <Input />
        </Form.Item>
      </Form>

此表格不:

      <Form initialValues={{ surname: 'Mouse'}}>
        <Form.Item name="surname">
          <Input />
          {null}
        </Form.Item>
      </Form>

唯一的区别是第二种形式中的

Form.Item
有两个孩子。

这背后有什么意图吗?


如果有人想知道我为什么问。所以像这样的东西破坏了形式:

<Form.Item name={name}>
  {type==="string" && <Input />}
  {type==="integer" && <InputNumber />}
</Form.Item>
antd
3个回答
4
投票

官方文档here给出了在一个

Form.Item
中使用多个子元素的示例。

<Form.Item label="Field">
    <Form.Item name="field" noStyle><Input /></Form.Item> // that will bind input
    <span>description</span>
</Form.Item>

您在

Form.Item
中放入的内容似乎有问题,即。
{null}
可能不允许。


2
投票

我找到了解决方案,现在对发生的事情有了更好的了解。

来自文档(https://ant.design/components/form/#Form.Item):

被Form.Item用name属性包裹后,value(或valuePropName定义的其他属性)onChange(或trigger定义的其他属性)props将被添加到表单控件中,表单数据的流向将由Form处理

文档中也有一个工作示例,这里是 codepen:https://codepen.io/pen?&editors=001

const {  useState  } = React;;
const {  Form, Input, Select, Button  } = antd;
const { Option } = Select;

const PriceInput = ({ value = {}, onChange }) => {
  const [number, setNumber] = useState(0);
  const [currency, setCurrency] = useState('rmb');

  const triggerChange = (changedValue) => {
    onChange?.({
      number,
      currency,
      ...value,
      ...changedValue,
    });
  };

  const onNumberChange = (e) => {
    const newNumber = parseInt(e.target.value || '0', 10);

    if (Number.isNaN(number)) {
      return;
    }

    if (!('number' in value)) {
      setNumber(newNumber);
    }

    triggerChange({
      number: newNumber,
    });
  };

  const onCurrencyChange = (newCurrency) => {
    if (!('currency' in value)) {
      setCurrency(newCurrency);
    }

    triggerChange({
      currency: newCurrency,
    });
  };

  return (
    <span>
      <Input
        type="text"
        value={value.number || number}
        onChange={onNumberChange}
        style={{
          width: 100,
        }}
      />
      <Select
        value={value.currency || currency}
        style={{
          width: 80,
          margin: '0 8px',
        }}
        onChange={onCurrencyChange}
      >
        <Option value="rmb">RMB</Option>
        <Option value="dollar">Dollar</Option>
      </Select>
    </span>
  );
};

const Demo = () => {
  const onFinish = (values) => {
    console.log('Received values from form: ', values);
  };

  const checkPrice = (_, value) => {
    if (value.number > 0) {
      return Promise.resolve();
    }

    return Promise.reject(new Error('Price must be greater than zero!'));
  };

  return (
    <Form
      name="customized_form_controls"
      layout="inline"
      onFinish={onFinish}
      initialValues={{
        price: {
          number: 0,
          currency: 'rmb',
        },
      }}
    >
      <Form.Item
        name="price"
        label="Price"
        rules={[
          {
            validator: checkPrice,
          },
        ]}
      >
        <PriceInput />
      </Form.Item>
      <Form.Item>
        <Button type="primary" htmlType="submit">
          Submit
        </Button>
      </Form.Item>
    </Form>
  );
};

ReactDOM.render(<Demo />, mountNode);


0
投票

将元素包裹在

<Input.Group>
内可以很好地适应上述场景。检查下面的代码

<Form.Item label="Role">
  <Input.Group compact>
    {error?.type === "getRulesError" && (
      <Alert message="Error fetching roles" type="error" showIcon />
    )}
    {!error?.type && rolesLoading && <Loading />}
    {!error?.type && !rolesLoading && (
      <Form.Item
        name="role"
        rules={[
          {
            required: true,
            message: "Please select user role"
          }
        ]}
        noStyle
      >
        <Select
          placeholder="Select user role"
          style={{ width: "100%" }}
        >
          {roles?.map(each => (
            <Option value={each.roleName} key={each.roleId}>
              {each?.roleName}
            </Option>
          ))}
        </Select>
      </Form.Item>
    )}
  </Input.Group>
</Form.Item>
© www.soinside.com 2019 - 2024. All rights reserved.