【问题标题】:how to get value of checkbox in react js如何在反应js中获取复选框的值
【发布时间】:2021-08-16 20:01:58
【问题描述】:

我正在尝试检索我的复选框的检查值,但我得到空值这是我的代码

<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="all" id="all" />
  <label className="form-check-label"  name="all" id="all">ALL</label>
</div>
</form>

还有我的方法:

constructor(props){
    super(props)
    this.state={
      rfp:"",
      rfx:"",
      rfp_x:"",
      all:"",
    
 
    }
    this.onChange =  this.onChange.bind(this);
    this.onSubmit = this.onSubmit.bind(this);
   }
  onChange(e){
    this.setState({[e.target.name] : e.target.value});}
  onSubmit(e){
    e.preventDefault();
    const FilterRegion={
  
      rfx:this.state.rfx,
      rfp:this.state.rfp,
      rfp_x:this.state.rfp_x,
      all:this.state.all,
    }
    console.log(FilterRegion)
   }

和我提交表单时的屏幕:

https://gyazo.com/32a24813545ebf7d3a48b72be724a76f

请尝试解决我的问题并显示我的复选框的值或名称!我该怎么办

【问题讨论】:

    标签: reactjs forms checkbox react-redux


    【解决方案1】:

    当使用受控组件时,您不会获得值,您只需将其提供给 HTML:您的 javascript 状态是事实的来源。也就是说,您应该进行以下更改:

    对复选框值使用布尔值:

    this.state = {
      rfp: false,
      rfx: false,
      rfp_x: false,
      all: false
    };
    

    使用event.target.checked 代替event.target.value:

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

    演示:https://codesandbox.io/s/polished-bush-5mf1n?file=/src/App.js

    【讨论】:

    • 如果我需要同时使用“event.target.checked”和“event.target.value”,那么如何使用呢?
    • 您可以使用 const { name, checked, value } = event.target 并使用 name、checked 和 value 变量
    【解决方案2】:

    首先使用react setState

     var [value,setvalue]=useState(false)
    
    <div className="form-check">
            <input className="form-check-input" checked={value} onChange={(e)=>setValue(e.target.checked)} type="checkbox"  />
           <label className="form-check-label">chechbox value</label>
           {value}
         </div>
    

    注意我正在使用 react 和 bootstrap css

    【讨论】:

      猜你喜欢
      • 2021-07-18
      • 1970-01-01
      • 1970-01-01
      • 2022-11-09
      • 1970-01-01
      • 1970-01-01
      • 2023-02-08
      • 2022-09-23
      • 1970-01-01
      相关资源
      最近更新 更多