首页 > 解决方案 > 根据所选选项填充 Antd 输入值

问题描述

我想根据之前选择的名称填充一个输入值。例如,如果我选择“FRANCILIENNE CONSEIL”,我希望关联的正确 IBAN 作为输入值。

我尝试了几件事但没有成功。

这是我的代码的堆栈闪电战:https ://stackblitz.com/edit/react-rc3me7

标签: reactjsantd

解决方案


你可以创建一些states来处理select option&input的初学者。然后通过您的handleChangeBeneficiary函数更新它们。

import React, { useState } from 'react'

const Demo = () => {
  const [beneficiary, setbeneficiary] = useState()
  const [iban, setiban] = useState()

  const handleChangeBeneficiary = (value) => {
    console.log(`selected ${value}`);
    setbeneficiary(value)

    // get selected iban
    const selected = beneficiaries?.find(item => item?.beneficiaryId == value)
    setiban(selected?.iban)
  };

  const onFinish = (values) => {
    console.log('Success:', values);
  };

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

  const beneficiaries = [
    {
      iban: 'FR76167LQSDKJLKSQJ86538089',
      name: 'FRANCILIENNE CONSEIL',
      bic: 'TRZOFR21XXX',
      beneficiaryId: '60c38ddf-63f9-4589-888b-27b7e1a50e53',
    },
    {
      iban: 'FR291001DSKLFJSLKJ8633Z17',
      name: 'MR NAMLA EMAD',
      bic: 'PSSTFRPPCNE',
      beneficiaryId: '60a11891-81ba-4ab2-9b92-ce4f461c2d50',
    },
  ];
  return (
    <Form
      {...layout}
      name="test"
      onFinish={onFinish}
      onFinishFailed={onFinishFailed}
      autoComplete="off"
    >
      <Form.Item label="Nom du bénéficiare" name="benef">
        <Select
          // defaultValue=""
          value={beneficiary}
          style={{ width: 300, marginBottom: 20 }}
          onChange={handleChangeBeneficiary}
        >
          {beneficiaries.map((nom) => (
            <Option value={nom.beneficiaryId}> {nom.name} </Option>
          ))}
        </Select>
      </Form.Item>
      <Form.Item label="IBAN" name="iban">
        <Input 
          // autoComplete="off" 
          style={{ marginBottom: 20 }}
          placeholder={iban} 
        disabled/>
      </Form.Item>
      <Form.Item wrapperCol={{ ...layout.wrapperCol, offset: 8 }}>
        <Button type="primary" htmlType="submit">
          Submit
        </Button>
      </Form.Item>
    </Form>
  );
};

推荐阅读