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;

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM