【问题标题】:How to add react-phone-number-input to -react-final-form?如何将 react-phone-number-input 添加到-react-final-form?
【发布时间】:2019-04-15 10:37:32
【问题描述】:

我目前正在使用react-final-form 创建一个表单,并尝试通过作为适配器集成使用react-phone-number-input,如this example 所示。

我尝试使用示例来了解它是如何完成的,但我不确定如何访问该组件并为其正确创建适配器。

import React from 'react';
import { Form, Field } from 'react-final-form';
import PhoneInput from 'react-phone-number-input';

const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))

const onSubmit = async values => {
  await sleep(300)
  window.alert(JSON.stringify(values, 0, 2))
}

const PhoneAdapter = ({ input, meta, ...rest }) => (
    <PhoneInput
    {...input}
    {...rest}
    value={input.value}
    onChange={(event, value) => input.onChange(value)}
  />
  )

class ContactForm extends React.Component {
    render() {
        return (
            <>
            <Form
              onSubmit={onSubmit}
              initialValues={{ }}
              render={({ handleSubmit, form, submitting, pristine, values }) => (
                <form onSubmit={handleSubmit}>
                  <fieldset>
                  <Field component={PhoneAdapter} />
                  </fieldset>
                  <fieldset>
                    <button type="submit" disabled={submitting || pristine}>
                      Submit
                    </button>
                  </fieldset>
                  <pre>{JSON.stringify(values, 0, 2)}</pre>
                </form>
              )}
            />
            </>
        );
    }
}

export default ContactForm;

【问题讨论】:

    标签: reactjs react-final-form


    【解决方案1】:

    更新:2019 年 7 月

    显然,您需要做的就是传播Field的输入属性。完美运行。如果您不熟悉传播,请了解传播。

    const PhoneAdapter = ({ input }) => (
        <PhoneInput {...input} />
    )
    
    <Field name="phone" placeholder="Enter phone number" component={PhoneAdapter} />
    

    我最终尝试了 FieldRenderProps 道具,直到成功。我不太确定它是否会起作用,因为react-phone-number-input 是一个组件中的两个元素。我认为它只会在其中一个元素上实现输入。

    通过使用input,我可以访问输入的道具。因此,我调用了它的值,因为默认值如下所示:

    <PhoneInput
      placeholder="Enter phone number"
      value={ this.state.value } // This is what I called.
      onChange={ value => this.setState({ value }) }/>
    

    然后我对 onChange 函数道具做了同样的事情。

    const PhoneAdapter = ({ input }) => (
        <PhoneInput value={input.value.value} onChange={value => input.onChange(value)} />
    )
    

    最后,我像这样使用了组件适配器:

    <Field name="phone" placeholder="Enter phone number" component={PhoneAdapter} />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-02-09
      • 2022-07-10
      • 2020-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-15
      相关资源
      最近更新 更多