最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Getting checkbox state in React JS - Stack Overflow

programmeradmin1浏览0评论

My code is as follows :

 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>
        );
    }
}

I'm mapping through my data and depending on fuel field I'm rendering checkboxes. Thus, I do not want to change the code if my data is changed. But now I have problem to get check if the checkbox is checked or not.

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

And then in the render I need somehow to get the state active. I tried with something like let checkboxState = Object.keys(this.state.values).length > 0 ? this.state.values.filter(i => i.type === v).active : false; , but it didn't worked.

Any advice?

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

My code is as follows :

 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>
        );
    }
}

I'm mapping through my data and depending on fuel field I'm rendering checkboxes. Thus, I do not want to change the code if my data is changed. But now I have problem to get check if the checkbox is checked or not.

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

And then in the render I need somehow to get the state active. I tried with something like let checkboxState = Object.keys(this.state.values).length > 0 ? this.state.values.filter(i => i.type === v).active : false; , but it didn't worked.

Any advice?

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"
    }
]
Share Improve this question edited Sep 16, 2016 at 10:10 Shubham Khatri 282k58 gold badges431 silver badges411 bronze badges asked Sep 16, 2016 at 9:08 BokyBoky 12.1k30 gold badges101 silver badges172 bronze badges 1
  • How does allCarsInTheList looks like – Ilanus Commented Sep 16, 2016 at 10:01
Add a ment  | 

2 Answers 2

Reset to default 1

You're accidentally passing in v rather than event into your click handler. To help stop confusion, I'd add the bind in the constructor.

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

Then your checkbox bees a bit easier to read too:

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

ps, should checked={true} be defaultChecked={true}?

Hi @Boky You can try something like this, note this should work only when you have initial state from the start where you set the checkboxes to false or true. Because we run this.isChecked() as soon as the ponentDidMount I suggest you take the state you can use defaultChecked for "fake" status.. Can't fully understand what's going on but from what I see this should take you where you want. Good luck

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>
        );
    }
}
发布评论

评论列表(0)

  1. 暂无评论