zoukankan      html  css  js  c++  java
  • react单选框获取值

    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;
  • 相关阅读:
    java虚拟机之垃圾回收机制
    java虚拟机之JVM体系结构
    java虚拟机之JVM生命周期
    删除链表中重复的结点
    (二十一)java多线程之Executors
    (十八)java多线程之Callable Future
    (十六)java多线程之优先队列PriorityBlockingQueue
    (十九)java多线程之ForkJoinPool
    (二十)java多线程之ScheduledThreadPoolExecutor
    (六)java多线程之ReadWriteLock
  • 原文地址:https://www.cnblogs.com/luguankun/p/11161835.html
Copyright © 2011-2022 走看看