【问题标题】:checkbox whit React js and state带有 React js 和状态的复选框
【发布时间】:2020-11-27 21:45:48
【问题描述】:

我正在创建一个过滤表单来根据复选框过滤我的数据,复选框的值为真或假,但我不知道为什么我的值为undefined

我的代码:

构造函数:

constructor(props){
    super(props)
    this.state={
      rfp:false,
      rfx:false,
      rfp_x:false,
      allclassification: false,
    }
this.onChange =  this.onChange.bind(this);
    this.onSubmit = this.onSubmit.bind(this);
   }

onChange:

onChange(e){
    this.setState({ [e.target.name]: e.target.checked });
}

onSubmit:

onSubmit(e){
    e.preventDefault();
    const FilterClassification = {
        // classification
        rfx:this.state.rfx,
        rfp:this.state.rfp,
        rfp_x:this.state.rfp_x,
        allclassification:this.state.allclassification,
    }
    console.log(FilterClassification)

    axios.post("http://localhost:8080/MenuFiltre/filtreregioncloser",FilterClassification )
}

HTML:

<form onSubmit={this.onSubmit}>
<fieldset>
<legend>RFX/RFP:</legend>
<div className="form-check">
  <input type="checkbox" className="form-check-input" onChange={this.onChange}  value={this.state.rfx} name="rfx" id="rfx" />
  <label className="form-check-label"  name="rfx">RFX</label>
  &nbsp; &nbsp; &nbsp; &nbsp;

  <input type="checkbox" className="form-check-input" onChange={this.onChange}  value={this.state.rfp}  name="rfp" id="rfp"  />
  
  <label className="form-check-label" >RFP</label>
  &nbsp; &nbsp; &nbsp; &nbsp;

  <input type="checkbox" className="form-check-input" onChange={this.onChange}  value={this.state.rfp_x}  name="rfp_x" id="rfp_x"/>
  <label className="form-check-label" >RFP(X)</label>
  &nbsp; &nbsp; &nbsp; &nbsp;


  <input type="checkbox" className="form-check-input"  onChange={this.onChange} name="allclassification" id="allclassification" />
  <label className="form-check-label"  name="all" id="all">ALL</label>
</div>
</from>

控制台结果界面:

我应该怎么做才能将undefined 更改为假值?

【问题讨论】:

    标签: reactjs checkbox axios state


    【解决方案1】:

    为复选框提供选中的属性而不是值

     <input type="checkbox" className="form-check-input" onChange={this.onChange}  
     checked={this.state.rfp_x}  name="rfp_x" id="rfp_x"/>
    

    而不是在构造函数中使用绑定函数 => 箭头函数

    • 像这样:- onSubmit=e=>{ //你的代码在这里 }
    • 对 onChange 执行相同操作并删除 this.onChange = this.onChange.bind(this); this.onSubmit = this.onSubmit.bind(this);在构造函数中

    【讨论】:

    • 我已经有同样的错误请你解释一下?
    • 只需在复选框输入中选中即可更改 value 属性
    猜你喜欢
    • 2020-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-30
    相关资源
    最近更新 更多