关于reactjs:显示在react-datetime选择器中选择的日期

Display the date selected in react-datetime picker

我想在UI上显示用户从日期时间选择器中选择的日期和时间。 我的代码如下-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import React from 'react';
import '../App.css';
import Datetime from 'react-datetime';

class Datetimepicker extends React.Component {
 constructor(props) {
    super(props);
    this.state = {
        moveaside: false,
        feed_items: [],
        newText: new Date(),
    };
    this.updateState = this.updateState.bind(this);
    this.showValuee = this.showValuee.bind(this);
}
updateState(e) {
    const text = e.value;
    console.log("text", text);
    this.setState({ newText: text });
    this.showValuee();
}
showValuee() {
    console.log(this.state.newText);
}
render() {
    console.log(this.props.value);
    return (
        <Datetime className={this.props.show ? 'rdt' : 'hide'} onChange={this.updateState} defaultValue={this.state.newText} />
    )
 }
}
export default Datetimepicker;

'文本'显示未定义的值。我正在父组件中导入此'Datetimepicker'组件,而我正在使用的Datetime选择器是-(https://github.com/YouCanBookMe/react-datetime)


您使用的反应日期时间选择器的文档以编程方式使用onChange功能,并且不会将更改event传递回用户。 相反,onChange中的参数是时刻日期对象本身。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      datetime: ''
    }
    this.updateState = this.updateState.bind(this);
  }
  updateState(date) {
    // This function gives you the moment object of date selected.
    console.log(date);
  }
  render() {
    return (
      <Datetime onChange={this.updateState}/>
    );
  }
}
ReactDOM.render(<App />, document.getElementById("root"));
1
2
3
4
5
6
7
8
<link rel="stylesheet" type="text/css" href="https://rawgit.com/arqex/react-datetime/master/css/react-datetime.css"/>



<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js">
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js">
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.3/moment.js">
<script src="https://rawgit.com/arqex/react-datetime/master/dist/react-datetime.js">

您应该查找的其他内容是如何使用setState回调。 因为setState是异步的,所以不能使用函数记录状态值。