gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 04:01:02 24 4
gpt4 key购买 nike

我目前正在使用 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;

最佳答案

更新:2019 年 7 月

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

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

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

我最终试验了 FieldRenderProps Prop ,直到成功为止。我不太确定它是否有效,因为 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 函数 prop 做了同样的事情。

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

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

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

关于reactjs - 如何将 react-phone-number-input 添加到-react-final-form?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55687357/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com