繁体   English   中英

在 React JS 中获取复选框 state

[英]Getting checkbox state in React 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>
        );
    }
}

我正在通过我的数据进行映射,并根据我正在渲染复选框的燃料场。 因此,如果我的数据发生更改,我不想更改代码。 但是现在我有问题要检查复选框是否被选中。

In handleFuel function I'm adding data to the state, and if checkbox is changed the state ( this.state.values ) should be something like {type: "Diesel", active: "True"} .

然后在渲染中,我需要以某种方式激活 state。 我尝试使用类似let checkboxState = Object.keys(this.state.values).length > 0? this.state.values.filter(i => i.type === v).active: false; let checkboxState = Object.keys(this.state.values).length > 0? this.state.values.filter(i => i.type === v).active: false; ,但没有奏效。

有什么建议吗?

更新

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"
    }
]

您不小心将v而不是 event 传递到您的点击处理程序中。 为了帮助避免混淆,我会在constructor中添加绑定。

this.handleFuel = this.handleFuel.bind(this);

然后你的复选框也变得更容易阅读:

<input type="checkbox" onChange={(e) => this.handleFuel(v, e)} checked={true}/>

ps, checked={true}应该是defaultChecked={true}吗?

嗨@Boky您可以尝试这样的事情,请注意,这只有在您从一开始就将复选框设置为false或true时具有初始state时才有效。 因为我们在componentDidMount后立即运行this.isChecked()我建议您使用 state 您可以将defaultChecked用于"fake"状态。无法完全理解发生了什么,但据我所知,这应该带您到您想要的地方. 祝你好运

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: {}
      };
      this.handleFuel = this.handleFuel.bind(this);
      this.isChecked = this.isChecked.bind(this);
    }

    handleFuel(name, event){
      let checkbox = event.target.checked;
      let nValues = _.clone(this.state.values);
      nValues.type = name;
      nValues.active = checkbox;
      this.setState({ values: nValues });
    }

    isChecked(name) {
      const { values } = this.state;
      let isChecked;
      const checkbox = values.find((c) => c.name === name);
      if (checkbox) isChecked = checkbox.active;
      return isChecked;
    } 

    render() {
        const { values } = this.state;
        const { language, allCarsInTheList } = this.props;
        return (
            <div>
              <div className="priceTitle" style={{padding: '5px 0'}}>
                {language.fuel}
              </div>
              <div className="transmissionValues">
                {_.uniq(allCarsInTheList.map(i => i.fuel)).map((name, i) => (
                  <div key={i}>
                    <input
                      type="checkbox"
                      onChange={(event) => this.handleFuel(name, event)}
                      checked={this.isChecked(name)}
                    />
                    <span>{name}</span>
                  </div>
                ))}
              </div>
            </div>
        );
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM