如何设置单选按钮默认签入反应?

时间:2019-07-14 18:14:17

标签: javascript html reactjs jsx

我创建了带有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

2 个答案:

答案 0 :(得分:1)

在首次安装时为要设置为选中的defaultChecked无线电添加input属性。

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

答案 1 :(得分:1)

您的代码实际上正在工作。您只需要在返回后加入括号。

在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);