react单选框获取值

Posted on   猫头唔食鱼  阅读(4031)  评论(0编辑  收藏  举报

react的input的每一种类型都要绑定onChange事件的,绑定onChange事件要传入事件对象的

react的单选框需要绑定checked属性的

 

复制代码
import React, { Component } from 'react'
class App extends Component {
  constructor(props) {
    super(props);
    this.state = { 
      sex:"0" // 定义选中的值,如果为空字符串,则默认不选中
     }
  }
  render() { 
    return (
        <div>
          <input type="radio" name="" value="0" checked={this.state.sex==0} onChange={(e)=>this.getValue(e)}/><label htmlFor="man">男</label>
          <input type="radio" name="" value="1" checked={this.state.sex==1} onChange={(e)=>this.getValue(e)}/><label htmlFor="woman">女</label>
        </div>
      );
  }
  getValue=(event)=>{
    //获取单选框选中的值
    console.log(event.target.value);
    this.setState({
      sex:event.target.value
    })
  }
}
 
export default App;
复制代码

 

循环input选项的写法:

复制代码
import React, { Component } from 'react'
class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      items: ["星期一", "星期二", "星期三"],
      item: "1"
    }
  }
  render() {
    return (
      <div>
        {
          this.state.items.map((ele, index) => {
            return (
              <p key={index}>
              {/* 如果控制台有警告 Expected '===' and instead saw '=='  eqeqeq 不用改成三个等号 */}
                <input type="radio" name="group" value={index} checked={this.state.item == index} onChange={(e) => this.getValue(e)} /><span>{ele}</span>
              </p>
            )
          })
        }
      </div>
    );
  }
  getValue = (e) => {
    this.setState({
      item: e.target.value
    })
  }
}

export default App;
复制代码

 

编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示