【问题标题】:How to access field data in other field如何访问其他字段中的字段数据
【发布时间】:2019-09-27 10:25:10
【问题描述】:

我有一个模态表单,其表单使用Formik。这里有两张图片,显示了可以通过开关切换的表单的两种状态。最初,我将文本填充到可以动态添加的字段中,并使用 .
存储为数组 第二张图片显示了我如何切换到textarea。在那里,您还可以添加带有逗号的文本,这些文本将被转换为数组。

有什么方法可以在第一个屏幕的输入字段中填充数据,切换到textarea 并访问已经输入的数据。

我知道 formik 将这种状态保存在某个地方。但目前这些字段有一个单独的状态。 这是我的组件:

class ModalForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      disabled: true,
    };
  }

  onChange = () => {
    this.setState({
      disabled: !this.state.disabled,
    });
  };

  render() {
    var {
      visible = false,
      onCancel,
      onRequest,
      submitting,
      setSubscriberType,
      editing,
      subscriptionTypeString,
      tested,
      selectedGates,
    } = this.props;
    const { gateId } = selectedGates.length && selectedGates[0];
    const handleSubmit = values => {
      console.log(values);
      onRequest && onRequest({ gateId, ...values });
    };
    const { disabled } = this.state;
    return (
      <Modal
        footer={null}
        closable
        title="Список абонентов для выбранного гейта"
        visible={visible}
        onCancel={onCancel}
        onOk={handleSubmit}
        destroyOnClose
        width="600px"
      >
        <StyledDescription>
          <Switch onChange={this.onChange} />
          <StyledLabel>массовый ввод</StyledLabel>
        </StyledDescription>
        <Formik
          initialValues={{ abonents: [''] }}
          onSubmit={handleSubmit}
          render={({ values, handleChange }) => (
            <Form>
              {disabled ? (
                <FieldArray
                  name="abonents"
                  render={arrayHelpers => {
                    return (
                      <div>
                        {values.abonents.map((value, index) => (
                          <div key={index}>
                            <MyTextInput
                              placeholder="Абонент ID"
                              name={`abonents.${index}`}
                              value={value}
                              onChange={handleChange}
                            />
                            <Button
                              shape="circle"
                              icon="delete"
                              onClick={() => {
                                arrayHelpers.remove(index);
                              }}
                            />
                          </div>
                        ))}

                        <Button type="dashed" onClick={() => arrayHelpers.push('')}>
                          <Icon type="plus" />Добавить абонента
                        </Button>
                      </div>
                    );
                  }}
                />
              ) : (
                <StyledField
                  placeholder="Введите ID абонентов через запятую"
                  name="message"
                  component="textarea"
                />
              )}

              <Footer>
                <Button type="primary" htmlType="submit">
                  Запросить
                </Button>
              </Footer>
            </Form>
          )}
        />
      </Modal>
    );
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.0.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.0.0/umd/react-dom.production.min.js"></script>

【问题讨论】:

    标签: reactjs antd formik


    【解决方案1】:

    很简单,formik 将值存储在 values.abonents 中,因此您可以在 textarea 中使用它

    let { Formik, Form, Field, ErrorMessage, FieldArray }  = window.Formik;
    function App () {
      const [disabled, setDisabled] = React.useState(false) // some boilerplate code
      function submit (values) {
        console.log('submit', values)
      }
      return (
        <Formik
          initialValues={{ abonents: [] }}
          onSubmit={submit}
          render={({ values, handleChange, setFieldValue }) => (
            <Form>
              <FieldArray
                name='abonents'
                render={arrayHelpers => {
                  if (!disabled) {
                    return (
                      <textarea onChange={(e) => {
                        e.preventDefault()
                        setFieldValue('abonents', e.target.value.split(', '))
                      }} value={values.abonents.join(', ')}></textarea>
                    )
                  }
                  return (
                    <div>
                      {
                        values.abonents.map((value, index) => (
                          <div key={index}>
                            <input
                              placeholder='Абонент ID'
                              name={`abonents.${index}`}
                              value={value}
                              onChange={handleChange}
                            />
                            <button onClick={(e) => {
                              e.preventDefault()
                              arrayHelpers.remove(index)
                            }}>
                              -
                            </button>
                          </div>
                        ))
                      }
    
                      <button onClick={(e) => {
                        e.preventDefault()
                        arrayHelpers.push('')
                      }}>
                        +
                      </button>
                    </div>
                  )
                }}
              />
              <button type='submit'>Submit</button>
              <button onClick={e => {
                e.preventDefault()
                setDisabled(!disabled)
              }}>toggle</button>
            </Form>
          )}
        />
      )
    }
    
    ReactDOM.render(<App />, document.querySelector('#root'))
    <script src="https://unpkg.com/react@16.9.0/umd/react.development.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.9.0/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/formik/dist/formik.umd.production.js"></script>
    <div id='root'></div>

    【讨论】:

      【解决方案2】:

      我找到了解决方案。您必须为输入和文本区域提供相同的名称,因此在输入中添加文本时会自动更改文本区域中的文本

                               <FieldArray
                    name="abonents"
                    render={arrayHelpers => {
                                  
                                 

                     <StyledField
                        placeholder="Введите ID абонентов через запятую"
                        name="abonents"
                        component="textarea"
                      />

      这两个字段具有相同的名称,因此它们可以互换呈现,但它们内部有共同的文本

      【讨论】:

      • 这是错误的,textarea 需要字符串值,fieldarray 需要数组值
      猜你喜欢
      • 2020-07-03
      • 2020-11-02
      • 1970-01-01
      • 2012-06-09
      • 1970-01-01
      • 2021-11-01
      • 2015-12-02
      • 2021-08-14
      • 2020-09-29
      相关资源
      最近更新 更多