我正在使用 Gatsbyjs 设置联系表单,并且需要一个日期选择器。是否可以在无状态组件上使用 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,
/>