javascript - 是否可以在无状态组件上使用 react-dates?
问题描述
我正在使用 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,
/>
解决方案
尝试像这样注入“this”作为道具:
const ContactForm = (props) => ( ...
// props.that ....
)
// call it where you need it
<ContactForm
that = {this}
...
>
...
</ContactForm>
推荐阅读
- html - 如何以角度在一个csv文件中导出多个html表?
- android - GDB 显示“无法在核心文件中找到映射”
- javascript - 嵌套动态高度过渡效果
- java - 我的 gradle 同步不适用于 Intellij Idea
- php - 如何修复 Laravel 8 中的“此路由不支持 GET 方法”错误?
- blazor - 如何从 Blazor 调用 javascript 函数并取回数据(网络摄像头应用视频流并保存屏幕截图)?
- telegram - 如何排除名字中含有违禁词的访客?
- c - 删除循环双向链表中给定位置的节点
- api - 如何将相机套件(Snapchat API)集成到 Android Studio?
- java - 在 java 中,在 lambda 函数中使用时,三元运算符是否被视为单行表达式?