我是ReactJS的新手,试图获取已选中/已选中复选框的值以及输入类型日期中的日期选择。但无法实现。
当我点击Generate Report
按钮时,您可以看到控制台显示状态。只保存位置,而不是其他选项。
以下是更新状态值和初始状态值的函数:
getInitialState: function() {
return {
selectedLocation: locationList[0].value,
selectedServiceType: [],
selectedStDate:new Date(1446887898),
selectedEdDate:new Date(1446887898)
};
},
selectServiceType:function(e){
selectedTypes.indexOf(e.target.value)? selectedTypes.push(e.target.value):console.log('Already exists in array');
this.setState({
selectedServiceType: e.target.checked
})
},
changeHandler: function(e) {
this.setState({
selectedLocation: e.target.value
})
},
selectStDate: function(e) {
this.setState({
selectedDate: e.target.value
})
},
selectEdDate: function(e) {
this.setState({
selectedEdDate: e.target.value
})
},
这里有完整的演示 JSFiddle
非常感谢
答案 0 :(得分:0)
我已经完成了重构,您可以查看它,Example
var FulfilmentReport = React.createClass({
getInitialState: function() {
return {
services: this.props.services,
location: this.props.locations[1].value,
startDate: this.formatDate(new Date(1446887898)),
endDate: this.formatDate(new Date(1446887898))
};
},
changeService: function (e) {
var services = this.state.services.map(function (service) {
service.checked = (service.value === e.target.value) ? !service.checked : service.checked;
return service;
});
this.setState({
services: services
});
},
handleChange: function(field, e) {
var data = {};
data[field] = e.target.value;
this.setState(data);
},
render: function() {
var buttonClasess = [
'right', 'mdl-button', 'mdl-js-button', 'mdl-button--raised',
'mdl-js-ripple-effect', 'mdl-button--colored'
].join(' ');
var services = this.state.services.map(function (service) {
return [
<label>{ service.name }</label>,
<input
type="checkbox"
name={service.value}
value={service.value}
checked={service.checked}
onChange={ this.changeService } />
];
}, this)
var locations = this.props.locations.map(function (location, index) {
return (<option key={index} value={ location.value }>{ location.name }</option>);
});
var elements = [{
label: <label>Location</label>,
data: <select
onChange={ this.handleChange.bind(this, 'location') }
value={ this.state.location }>{ locations }</select>
}, {
label: <label>Service Type</label>,
data: <div>{ services }</div>
},{
label: <label>Start Date</label>,
data: <input
type="date"
value={ this.state.startDate }
onChange={ this.handleChange.bind(this, 'startDate') } />
},{
label: <label>'End Date'</label>,
data: <input
type="date"
value={ this.state.endDate }
onChange={ this.handleChange.bind(this, 'endDate') } />
}];
elements = elements.map(function (element) {
return [element.label, element.data];
});
return (<div id="items">
<div>{ elements }</div>
<input type="button" value="Generate Report" onClick={ this.onItemClick } className={ buttonClasess } />
</div>);
},
onItemClick: function() {
this.state.services = this.state.services.filter(function (el) {
return el.checked;
}) ;
console.log( this.state );
},
formatDate: function (date) {
return date.toISOString().slice(0, 10);
}
});