簡體   English   中英

如何設置單選按鈕默認選中反應?

[英]How to Set radio button default checked in react?

我用 3 個單選按鈕創建了單選按鈕:我想將石灰作為默認選中的單選按鈕,我將石灰設置為默認值但它不起作用。

這是我的代碼我不知道如何解決我的問題。

    import React, {Component} from 'react';

    class App extends Component{
      constructor(props){
        super(props)

        this.handleflavorSubmit = this.handleflavorSubmit.bind(this)
        this.onChangeRadio = this.onChangeRadio.bind(this)


        this.state = {value : 'lime'};
        }

      onChangeRadio(e){
        this.setState({value : e.target.value})
      }

      handleflavorSubmit(e){
        alert("your favorite flavor is " + this.state.value)
        e.preventDefault();
      }

      render(){

        return( 
          <div>
            <h1>Choose your flavor:</h1>
            <form onSubmit = {this.handleflavorSubmit}>
              <input type="radio" checked = {this.state.value === 'grapefruit'} onChange = {this.onChangeRadio} value= "grapefruit"/>Grapefruit
              <input type = "radio" checked = {this.state.value === 'lime'} onChange = {this.onChangeRadio} value = "lime"/>Lime
              <input type = "radio" checked = {this.state.value === 'orange'} onChange = {this.onChangeRadio} value = "orange"/>Orange
              <input type = "submit" value = "submit"/>
            </form>

          </div>
        )
      }
    }

export default App

為要在第一次安裝時設置為已選中的input無線電添加defaultChecked屬性。

<input type = "radio" defaultChecked checked = {this.state.value === 'lime'} onChange = {this.onChangeRadio} value = "lime"/>Lime

您的代碼實際上正在運行。 您只需要在返回后包含括號。

在 CodeSandbox 中嘗試一下。 這是工作代碼: https : //codesandbox.io/s/red-rain-r81n4

import React,{Component} from "react";
import ReactDOM from "react-dom";


import "./styles.css";

class App extends Component{
  constructor(){
    super()

    this.handleflavorSubmit = this.handleflavorSubmit.bind(this)
    this.onChangeRadio = this.onChangeRadio.bind(this)


    this.state = {value : 'lime'};
    }

  onChangeRadio(e){
    this.setState({value : e.target.value})
  }

  handleflavorSubmit(e){
    alert("your favorite flavor is " + this.state.value)
    e.preventDefault();
  }

  render(){

    return (
      <div>
        <h1>Choose your flavor:</h1>
        <form onSubmit = {this.handleflavorSubmit}>
          <input type="radio" checked = {this.state.value === 'grapefruit'} onChange = {this.onChangeRadio} value= "grapefruit"/>Grapefruit
          <input type = "radio" checked = {this.state.value === 'lime'} onChange = {this.onChangeRadio} value = "lime"/>Lime
          <input type = "radio" checked = {this.state.value === 'orange'} onChange = {this.onChangeRadio} value = "orange"/>Orange
          <input type = "submit" value = "submit"/>
        </form>
      </div>
    );
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App/>, rootElement);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM