簡體   English   中英

如何將 react-phone-number-input 添加到-react-final-form?

[英]How to add react-phone-number-input to -react-final-form?

我目前正在使用react-final-form創建一個表單,並嘗試通過作為適配器集成來使用react-phone-number-input ,如本示例所示

我試圖使用該示例來了解它是如何完成的,但我不確定如何訪問該組件並為其正確創建適配器。

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;

更新: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} />

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM