【问题标题】:Set checkbox value in React JS在 React JS 中设置复选框值
【发布时间】:2017-01-06 13:00:49
【问题描述】:

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

我有这样的事情:

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

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

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

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

在我的示例中不起作用。

有什么想法吗?

【问题讨论】:

  • 你确定它是 OR 吗? (||) 你说When user changes the values of the price range slider to their initial values (min and max values)
  • 如果其中一个值不等于最小值和最大值,则表示用户更改了价格滑块,对吧?
  • 如果 ONE 不相等(假设您更改了 A 而不是 BA == 初始值|| B == 初始值将评估为 TRUE,而不是更改 A 或 B 将导致相同的结果,并且仅更改两者都会返回 TRUE,因此正如您正确地说,如果其中一个不是初始的,您不希望它返回 TRUE,因此它是一个 AND 运算符)。此外我不知道您的代码中是否还有更多错误,但是更改 ||对于 && 是一个好的开始。 :)
  • 如果其中一个不是最初的,我想返回 true。如果最小值 == 0 和最大值 == 20000,如果 A 由 0 变为 1000 且 B 相同,则为 20000;然后我想将复选框更改为 true。

标签: javascript reactjs checkbox


【解决方案1】:

这有点旧,但万一它有帮助。

我开始依赖这种语法

在类中声明一个存储状态的变量:

const [agreeToAllTerms, setAgreeToAllTerms] = useState(false);

声明复选框

<Checkbox checked={agreeToAllTerms} onChange={(event)=> {handleChangeChk(event)}}/> 

然后在函数中像这样检查复选框的当前状态。

const handleChangeChk = (chkValue) => {
    setAgreeToAllTerms(chkValue.target.checked);
}

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        【解决方案4】:

        不确定但试试看:

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

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

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

        【讨论】:

          【解决方案5】:

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

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

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

          然后将其传递给您的 handleChange this.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

          【讨论】:

            猜你喜欢
            • 2022-07-11
            • 2015-09-28
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-08-28
            • 2017-12-29
            • 2016-12-31
            • 1970-01-01
            相关资源
            最近更新 更多