Javascript 在 React JS 中设置复选框值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39224165/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:20:44  来源:igfitidea点击:

Set checkbox value in React JS

javascriptreactjscheckbox

提问by Boky

I'm trying to change the value of the checkbox with the onChangefunction of another input field.

我正在尝试使用onChange另一个输入字段的功能更改复选框的值。

I have something like this:

我有这样的事情:

class price extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            minValue: 0,
            maxValue: 20000,
            step: 1000,
            firstValue: null,
            secondValue: null,
            chcboxValue: false
        };

        this.handleChange = this.handleChange.bind(this);
    }

    componentWillMount() {
        this.setState({firstValue: this.state.minValue, secondValue: this.state.maxValue});
    }

    handleChange(name, event) {
        let value = event.target.value;
        // We set the state value depending on input that is clicked
        if(name === "second") {
            if(parseInt(this.state.firstValue) < parseInt(value)) {
                this.setState({secondValue:value});
            }
        } else {
            // The first value can't be greater than the second value
            if(parseInt(value) < parseInt(this.state.secondValue)) {
                this.setState({firstValue: value});
            }
        }

        // We set the checkbox value
        if(parseInt(this.state.firstValue) != parseInt(this.state.minValue) || parseInt(this.state.secondValue) != parseInt(this.state.maxValue)) {
            this.setState({chcboxValue: true});
        } else {
            this.setState({chcboxValue: false});
        }
    }

    render() {
        const language = this.props.language;
        return (
            <div>
                <div className="priceTitle">{language.price}</div>
                <InputRange language={language}
                            firstValue={parseInt(this.state.firstValue)}
                            secondValue={parseInt(this.state.secondValue)}
                            minValue={parseInt(this.state.minValue)}
                            maxValue={parseInt(this.state.maxValue)}
                            step={parseInt(this.state.step)}
                            handleChange={this.handleChange}
                            chcboxValue={this.state.chcboxValue}/>
            </div>
        );
    }
}

My InputRangecomponent is something like this:

我的InputRange组件是这样的:

const inputRange = ({language, firstValue, secondValue, minValue, maxValue, step, handleChange, chcboxValue}) => {
    return (
        <div>
            <div className="rangeValues">Range : {firstValue} - {secondValue}</div>
            <section className="range-slider">
                <input type="checkbox" checked={chcboxValue} />
                <input type="range" value={firstValue} min={minValue} max={maxValue} step={step}  onChange={handleChange.bind(this, "first")} />
                <input type="range" value={secondValue} min={minValue} max={maxValue} step={step} onChange={handleChange.bind(this, "second")} />
                <div className="minValue">{minValue}</div>
                <div className="maxValue">{maxValue}</div>
            </section>
        </div>
    );
};

The checkbox value on initial load is set to false. When the user changes the value of the price range slider, I want that the checkbox value to change to true.

初始加载时的复选框值设置为 false。当用户更改价格范围滑块的值时,我希望复选框值更改为 true。

When the user changes the value of the price range slider to their initial values (min and max values), I want the checkbox value to again change to false.

当用户将价格范围滑块的值更改为其初始值(最小值和最大值)时,我希望复选框值再次更改为 false。

It isn't working in my example.

它在我的例子中不起作用。

Any ideas?

有任何想法吗?

采纳答案by QoP

Your example is not working properly because you are checking the value before this.setState()is completed. Don't forget that this.setState()does not immediately mutate the state.

您的示例无法正常工作,因为您在this.setState()完成之前正在检查该值。不要忘记,this.setState()它不会立即改变state.

To fix it, you can create a function where you update the value of the checkbox

要修复它,您可以创建一个函数来更新复选框的值

updateCheckBox(){
   if(parseInt(this.state.firstValue) != parseInt(this.state.minValue) || parseInt(this.state.secondValue) != parseInt(this.state.maxValue)){
        this.setState({chcboxValue: true});
    }else{
        this.setState({chcboxValue: false});
    }
}

and then pass it to your handleChangethis.setState()calls.

然后将其传递给您的handleChangethis.setState()电话。

handleChange(name, event){
    let value = event.target.value;
    //We set the state value depending on input that is clicked
    if(name === "second"){
        if(parseInt(this.state.firstValue) < parseInt(value)){
            this.setState({secondValue:value}, this.updateCheckBox);
        }
    }else{
        //The first value can't be greater than the second value
        if(parseInt(value) < parseInt(this.state.secondValue)) {
            this.setState({firstValue: value}, this.updateCheckBox);
        }
  }

jsfiddle

提琴手

回答by Neeraj Prajapati

not sure but try it :

不确定,但试试看:

React.createElement('input',{type: 'checkbox', defaultChecked: false});

or

或者

<input type="checkbox" checked={this.state.chkbox} onChange={this.handleChangeChk} />

or

或者

var Checkbox = React.createClass({
  getInitialState: function() {
    return {
      isChecked: true
    };
  },
  toggleChange: function() {
    this.setState({
      isChecked: !this.state.isChecked // flip boolean value
    }, function() {
      console.log(this.state);
    }.bind(this));
  },
  render: function() {
    return (
      <label>
        <input
          type="checkbox"
          checked={this.state.isChecked}
          onChange={this.toggleChange} />
        Check Me!
      </label>
    );
  }
});

React.render(<Checkbox />, document.getElementById('checkbox'));

回答by DanielKhan

Here is a generic form change handler that also supports checkboxes

这是一个通用的表单更改处理程序,它也支持复选框

 onFormChange: (e) => {
    // In my example all form values are stored in a state property 'model'
    let model = this.state.model;

    if(e.target.type == 'checkbox') {

      if(model[e.target.name] === false) {
        model[e.target.name] = true;
      } else if(model[e.target.name] === true) {
        model[e.target.name] = false;
      } else {
        // if the property has not be defined yet it should be true
        model[e.target.name] = true;
      }
    } else {
      model[e.target.name] = e.target.value;
    }

    // Update the state
    this.setState({
      model: model
    });
  }

回答by Mr S Coder

you shoud know how we can bind html input value in react. here this example for beginer. easy to understand

你应该知道我们如何在 react 中绑定 html 输入值。这是初学者的这个例子。容易理解

const chk= true

chkchk() ={ console.log("checkbox event fire")}
<input name="abc"
 type="checkbox"  checked={chk.toString()}        
 onChange={chkchk} 
            />