我的代碼如下:獲取複選框狀態作出反應JS
import React from 'react';
import FontAwesome from 'react-fontawesome';
import {Link} from 'react-router';
import { filter_names } from './filterActions';
import _ from 'lodash';
export default class fuel extends React.Component {
constructor(props){
super(props);
this.state = {
values: {}
}
}
handleFuel(name, event){
let checkbox = event.target.checked;
let nValues = _.clone(this.state.values);
nValues.type = name;
nValues.active = checkbox;
this.setState({values: nValues});
}
render() {
const language = this.props.language;
return (
<div>
<div className="priceTitle" style={{padding: '5px 0'}}>{language.fuel}</div>
<div className="transmissionValues">
{_.uniq(this.props.allCarsInTheList.map(i => i.fuel)).map((v, i) => {
return (<div key={i}><input type="checkbox" onChange={this.handleFuel.bind(this, v)} checked={true}/> <span>{v}</span></div>);
})}
</div>
{/*<div className="transmissionValues">
<input type="checkbox" onChange={this.handleBenzine.bind(this)} checked={this.getFilterValues().checkboxBenzine}/> <span>Benzine</span>
</div>*/}
</div>
);
}
}
我映射通過我的數據,並根據燃料領域,我渲染複選框。因此,如果我的數據發生更改,我不想更改代碼。但現在我有問題檢查複選框是否被選中。
在handleFuel函數中,我將數據添加到狀態,如果複選框被更改,狀態(this.state.values
)應該是類似於{type: "Diesel", active: "True"}
。
然後在渲染中,我需要以某種方式讓狀態變爲活動狀態。我嘗試了類似let checkboxState = Object.keys(this.state.values).length > 0 ? this.state.values.filter(i => i.type === v).active : false;
,但它沒有奏效。
有什麼建議嗎?
UPDATE
let allCarsInTheList = [
{
id: 1,
listID: 3,
make: "Audi",
model: "Q5",
desc: "2.0 CR TDi Comfortline BMT",
price: 12484,
mileage: 120021,
fuel: "Diesel",
engine: '105/77',
chassis: "WAUZZZ4G4FN026103"
}, {
id: 2,
listID: 3,
make: "Audi",
model: "Q5",
desc: "2.0 CR TDi Comfortline BMT",
price: 12484,
mileage: 120021,
fuel: "Benzine",
engine: '105/77',
chassis: "WAUZZZ4G4FN026103"
}, {
id: 3,
listID: 3,
make: "Audi",
model: "Q5",
desc: "2.0 CR TDi Comfortline BMT",
price: 12484,
mileage: 120021,
fuel: "Diesel",
engine: '105/77',
chassis: "WAUZZZ4G4FN026103"
}, {
id: 4,
listID: 3,
make: "Audi",
model: "Q5",
desc: "2.0 CR TDi Comfortline BMT",
price: 12484,
mileage: 120021,
fuel: "Diesel",
engine: '105/77',
chassis: "WAUZZZ4G4FN026103"
}
]
allCarsInTheList如何看起來像 –