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

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

问题描述

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

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

我知道 formik 会将这种状态保留在某处.但目前这些字段有一个单独的状态.这是我的组件:

class ModalForm extends React.Component {构造函数(道具){超级(道具);this.state = {禁用:真,};}onChange = () =>{this.setState({禁用:!this.state.disabled,});};使成为() {无功{可见=假,取消,根据要求,提交,设置订阅者类型,编辑,订阅类型字符串,测试,选定的盖茨,} = this.props;const { gateId } = selectedGates.length &&选定的门[0];const handleSubmit = 值 =>{控制台日志(值);onRequest &&onRequest({ gateId, ...values });};const { 禁用 } = this.state;返回 (<模态页脚={空}可关闭的title="Список абонентов для выбранного гейта"可见={可见}onCancel={onCancel}onOk={handleSubmit}关闭时销毁宽度=600像素"><样式描述><Switch onChange={this.onChange}/><StyledLabel>массовый ввод</StyledLabel></StyledDescription><福米克initialValues={{ abonents: [''] }}onSubmit={handleSubmit}render={({ values, handleChange }) =>(<表格>{禁用?(<字段数组名称=abonents"渲染={arrayHelpers =>{返回 (<div>{values.abonents.map((value, index) => (<div key={index}><我的文本输入placeholder="Абонент ID"name={`abonents.${index}`}价值={价值}onChange={handleChange}/><按钮形状=圆圈"图标=删除"onClick={() =>{arrayHelpers.remove(index);}}/>

))}<Button type="dashed" onClick={() =>arrayHelpers.push('')}><Icon type="plus"/>Добавить абонента</按钮>

);}}/>) : (<样式字段placeholder="Введите ID абонентов через запятую"名称=消息"组件=文本区域"/>)}<页脚><Button type="primary" htmlType="submit">Запросить</按钮></页脚></表格>)}/></模态>);}}

<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 中使用它

let { Formik, Form, Field, ErrorMessage, FieldArray } = window.Formik;功能应用(){const [disabled, setDisabled] = React.useState(false)//一些样板代码函数提交(值){console.log('提交', 值)}返回 (<福米克initialValues={{ abonents: [] }}onSubmit={提交}render={({ values, handleChange, setFieldValue }) =>(<表格><字段数组名称='abonents'渲染={arrayHelpers =>{如果(!禁用){返回 (<textarea onChange={(e) =>{e.preventDefault()setFieldValue('abonents', e.target.value.split(', '))}} value={values.abonents.join(', ')}></textarea>)}返回 (<div>{values.abonents.map((value, index) => (<div key={index}><输入placeholder='Абонент ID'name={`abonents.${index}`}价值={价值}onChange={handleChange}/><button onClick={(e) =>{e.preventDefault()arrayHelpers.remove(index)}}>——

))}<button onClick={(e) =>{e.preventDefault()arrayHelpers.push('')}}>+

)}}/><button type='submit'>提交</button>

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.

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

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>

解决方案

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天全站免登陆