我正在开发一个React应用程序。我有3 div,每个都有DatePicker组件。我想更新选择的日期。当我更改日期时,每个div都会更新。
这是代码-
import React, { Component } from 'react';
import DatePicker from 'react-datepicker';
import moment from 'moment';
import './App.css';
import 'react-datepicker/dist/react-datepicker.css';
class Application extends React.Component {
constructor(props) {
super(props)
this.state = { date: moment() };
}
dateChanged = (d) => {
this.setState({ date: d });
}
render() {
return (
<div>
<div>
<DatePicker selected={this.state.date} onChange= {this.dateChanged} />
</div>
<div>
<DatePicker selected={this.state.date} onChange={this.dateChanged} />
</div>
<div>
<DatePicker selected={this.state.date} onChange={this.dateChanged} />
</div>
</div>
);
}
}
export default Application;
答案 0 :(得分:1)
这是怎么做。
import React, { Component } from 'react';
import DatePicker from 'react-datepicker';
import moment from 'moment';
import './App.css';
import 'react-datepicker/dist/react-datepicker.css';
class Application extends React.Component {
constructor(props) {
super(props)
this.state = { date1: moment(), date2: moment(), date3: moment() };
}
dateChanged = (provider, d) => {
this.setState({ [provider]: d });
}
render() {
return (
<div>
<div>
<DatePicker selected={this.state.date1} onChange={this.dateChanged.bind(this, "date1")} />
</div>
<div>
<DatePicker selected={this.state.date2} onChange={this.dateChanged.bind(this, "date2")} />
</div>
<div>
<DatePicker selected={this.state.date3} onChange={this.dateChanged.bind(this, "date3")} />
</div>
</div>
);
}
}
export default Application;
答案 1 :(得分:0)
为此,您需要在每个状态下提供一个键和值
import React, { Component } from 'react';
import DatePicker from 'react-datepicker';
import moment from 'moment';
import './App.css';
import 'react-datepicker/dist/react-datepicker.css';
class Application extends React.Component {
constructor(props) {
super(props)
this.state = { date1: moment(), date2: moment(), date3: moment() };
}
dateChanged = (provider, d) => {
this.setState({ [provider]: d });
}
render() {
return (
<div>
<div>
<DatePicker selected={this.state.date} onChange={this.dateChanged.bind(this, "date1")} />
</div>
<div>
<DatePicker selected={this.state.date} onChange={this.dateChanged.bind(this, "date2")} />
</div>
<div>
<DatePicker selected={this.state.date} onChange={this.dateChanged.bind(this, "date3")} />
</div>
</div>
);
}
}
export default Application;