如何访问其他字段中的字段数据 [英] How to access field data in other field

查看:58
本文介绍了如何访问其他字段中的字段数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a modal form with a form that uses Formik. Here are two pictures that show two states of that form that can be toggled with a switch.Initially I fill text into fields which can be added dynamically and stored as an array with .
The second picture shows how I toggled to textarea. There you can also add text with commas that will be turned into an array.

有没有办法在第一个屏幕的输入字段中填充数据,切换到textarea并访问已经输入的数据.

Is there any way to fill data in input fields from the first screen, toggle into textarea and access already inputted data.

我知道Formik将该状态保留在某个地方.但是目前,这些字段具有单独的状态. 这是我的组件:

I understand formik keeps that state somewhere. But at the moment these fields have a separate state. Here is my component:

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>

推荐答案

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

Pretty easy, formik stores values inside values.abonents, hence you can use it inside 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>

这篇关于如何访问其他字段中的字段数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆