我在组件中使用react-datepicker来更新帖子。日期和其他日期通过props从MongoDB传递到组件。这是一个具有CRUD功能的简单fullstack-graphql应用程序。也许问题在于正确的日期转换。通过props接收到的输入日期的格式为Unix Timestamp,例如“ 1573227729064”。 “日期选择器”格式应为“ MM / DD / YYYY”。我已经阅读了文档并配置了datepicker,但是由于某种原因它无法渲染。也许有人可以看下面的代码来解释我。非常感谢您的帮助!
import React, { Component } from 'react';
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
import { EditorState, getCurrentContent, getPlainText, ContentState } from 'draft-js';
import { Editor } from 'react-draft-wysiwyg';
import '../../node_modules/react-draft-wysiwyg/dist/react-draft-wysiwyg.css';
import { stateToHTML } from 'draft-js-export-html';
import gql from 'graphql-tag';
import { Mutation } from 'react-apollo';
import { stateFromHTML } from 'draft-js-import-html';
const updateMutation = gql`
mutation UpdateHeroMutation($id: ID!, $title: String!, $description: String!, $date: String!) {
updateHero(heroUpdate: {_id: $id, title: $title, description: $description, date: $date}) {
_id
title
description
date
}
}
`;
class Hero extends Component {
constructor(props) {
super(props);
this.state = {
title: props.data.title,
setDate: props.data.date,
editorState: EditorState.createWithContent(stateFromHTML(props.data.description))
};
}
onChange(e) {
this.setState({ title: e.target.value })
}
onChangeSelect(published) {
this.setState({ setDate: published })
}
onEditorStateChange = (editorState) => {
this.setState({
editorState
});
}
render() {
return (
<>
<h5>Edit post</h5>
<div className="label-section">Name:</div>
<h5>
<input name="title" id="title" type="text" defaultValue={this.props.data.title} onChange={e => this.onChange(e)} />
</h5>
<br />
<div className="label-section">Published:</div>
<DatePicker
id="published"
name="published"
defaultValue=""
dateFormat="MM/DD/YYYY"
selected={Date(this.state.setDate)}
onChange={published => this.onChangeSelect(published)}
/>
<h5>{this.state.setDate}</h5>
<div className="label-section">Edit text:</div>
<Editor
editorState={this.state.editorState}
wrapperClassName="demo-wrapper"
editorClassName="demo-editor"
onEditorStateChange={this.onEditorStateChange}
/>
<input type="text" className="hidden" defaultValue={this.props.data._id} />
<Mutation mutation={updateMutation} variables={{ id: this.props.data._id, title: this.state.title, description: stateToHTML(this.state.editorState.getCurrentContent()), date: this.state.setDate }}>
{updateHero => (
<button onClick={updateHero} type="submit">OK</button>
)}
</Mutation>
</>
);
}
}
export default Hero;
您需要初始化日期
this.state = {
title: props.data.title,
setDate: new Date(props.data.date),
editorState: EditorState.createWithContent(stateFromHTML(props.data.description))
};
和
<DatePicker
id="published"
name="published"
defaultValue=""
dateFormat="MM/DD/YYYY"
selected={this.state.setDate}
onChange={this.onChangeSelect}
/>