[英]Is it possibile to use react-dates on a stateless component?
我正在與Gatsbyjs建立聯系表格,需要一個日期選擇器。 是否可以在無狀態組件上使用react-date? 我試過但沒有成功(因為指令引用了一個類組件,我真的不知道如何在這里表現)。
這是我沒有react-dates的表單示例(我正在使用Formik):
import React from 'react'
import { Formik, Form, Field, ErrorMessage } from 'formik'
function encode(data) {
return Object.keys(data)
.map(key => encodeURIComponent(key) + "=" + encodeURIComponent(data[key]))
.join("&");
}
const ContactForm = () => (
<>
<h1>TITLE</h1>
<Formik
initialValues={{ email: '', name: '', start: '', end: '', message: '' }}
onSubmit={(values) => {
fetch("/", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: encode({
"form-name": "contact",
...values
})
})
.then(() => alert("Thanks!"))
.catch(error => alert(error))
}}
>
{({ isSubmitting }) => (
<Form name="contact" data-netlify="true" action="/grazie">
<input type="hidden" name="form-name" value="contact" />
<label>
<Field type="text" name="name" placeholder="Name and Surname" />
<ErrorMessage name="name" component="div" />
</label>
<br />
<label>
<Field type="email" name="email" placeholder="Email" required />
<ErrorMessage name="email" component="div" />
</label>
<br />
<button type="submit" disabled={isSubmitting}>Send</button>
</Form>
)}
</Formik>
</>
)
export default ContactForm
既然它是一個無狀態組件,我無法添加{this.etc.etc},所以我不知道如何配置react-dates。 這是我應該添加的代碼:
<DateRangePicker
startDate={this.state.startDate} // momentPropTypes.momentObj or null,
startDateId="your_unique_start_date_id" // PropTypes.string.isRequired,
endDate={this.state.endDate} // momentPropTypes.momentObj or null,
endDateId="your_unique_end_date_id" // PropTypes.string.isRequired,
onDatesChange={({ startDate, endDate }) => this.setState({ startDate, endDate })} // PropTypes.func.isRequired,
focusedInput={this.state.focusedInput} // PropTypes.oneOf([START_DATE, END_DATE]) or null,
onFocusChange={focusedInput => this.setState({ focusedInput })} // PropTypes.func.isRequired,
/>
嘗試將'this'作為支柱注入:
const ContactForm = (props) => ( ...
// props.that ....
)
// call it where you need it
<ContactForm
that = {this}
...
>
...
</ContactForm>
如果你想使用this
那么制作功能組件並不是一個好的用例,為什么不在這里制作類組件。 這真的很容易
由於這個答案,我解決了這個問題https://stackoverflow.com/a/55454138/2232626
我剛剛創建了一個帶有日期選擇器組件的組件,然后將其導入到主Formik頁面所在的位置。 這是一個工作示例: https : //codesandbox.io/s/723l233my1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.