How to use radio buttons in ReactJS?

前端 未结 10 2094
再見小時候
再見小時候 2020-11-27 10:05

I am new to ReactJS, sorry if this sounds off. I have a component that creates several table rows according to the received data.

Each cell within the column has a

相关标签:
10条回答
  • 2020-11-27 10:28

    Just an idea here: when it comes to radio inputs in React, I usually render all of them in a different way that was mentionned in the previous answers.

    If this could help anyone who needs to render plenty of radio buttons:

    import React from "react"
    import ReactDOM from "react-dom"
    
    // This Component should obviously be a class if you want it to work ;)
    
    const RadioInputs = (props) => {
      /*
        [[Label, associated value], ...]
      */
      
      const inputs = [["Male", "M"], ["Female", "F"], ["Other", "O"]]
      
      return (
        <div>
          {
            inputs.map(([text, value], i) => (
    	  <div key={ i }>
    	    <input type="radio"
                  checked={ this.state.gender === value } 
    	      onChange={ /* You'll need an event function here */ } 
    	      value={ value } /> 
        	    { text }
              </div>
            ))
          }
        </div>
      )
    }
    
    ReactDOM.render(
      <RadioInputs />,
      document.getElementById("root")
    )
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
    
    <div id="root"></div>

    0 讨论(0)
  • 2020-11-27 10:30

    Based on what React Docs say:

    Handling Multiple Inputs. When you need to handle multiple controlled input elements, you can add a name attribute to each element and let the handler function choose what to do based on the value of event.target.name.

    For example:

    class App extends React.Component {
      constructor(props) {
        super(props);
        this.state = {};
      }
    
      handleChange = e => {
        const { name, value } = e.target;
    
        this.setState({
          [name]: value
        });
      };
    
      render() {
        return (
          <div className="radio-buttons">
            Windows
            <input
              id="windows"
              value="windows"
              name="platform"
              type="radio"
              onChange={this.handleChange}
            />
            Mac
            <input
              id="mac"
              value="mac"
              name="platform"
              type="radio"
              onChange={this.handleChange}
            />
            Linux
            <input
              id="linux"
              value="linux"
              name="platform"
              type="radio"
              onChange={this.handleChange}
            />
          </div>
        );
      }
    }
    

    Link to example: https://codesandbox.io/s/6l6v9p0qkr

    At first, none of the radio buttons is selected so this.state is an empty object, but whenever the radio button is selected this.state gets a new property with the name of the input and its value. It eases then to check whether user selected any radio-button like:

    const isSelected = this.state.platform ? true : false;
    

    EDIT:

    With version 16.7-alpha of React there is a proposal for something called hooks which will let you do this kind of stuff easier:

    In the example below there are two groups of radio-buttons in a functional component. Still, they have controlled inputs:

    function App() {
      const [platformValue, plaftormInputProps] = useRadioButtons("platform");
      const [genderValue, genderInputProps] = useRadioButtons("gender");
      return (
        <div>
          <form>
            <fieldset>
              Windows
              <input
                value="windows"
                checked={platformValue === "windows"}
                {...plaftormInputProps}
              />
              Mac
              <input
                value="mac"
                checked={platformValue === "mac"}
                {...plaftormInputProps}
              />
              Linux
              <input
                value="linux"
                checked={platformValue === "linux"}
                {...plaftormInputProps}
              />
            </fieldset>
            <fieldset>
              Male
              <input
                value="male"
                checked={genderValue === "male"}
                {...genderInputProps}
              />
              Female
              <input
                value="female"
                checked={genderValue === "female"}
                {...genderInputProps}
              />
            </fieldset>
          </form>
        </div>
      );
    }
    
    function useRadioButtons(name) {
      const [value, setState] = useState(null);
    
      const handleChange = e => {
        setState(e.target.value);
      };
    
      const inputProps = {
        name,
        type: "radio",
        onChange: handleChange
      };
    
      return [value, inputProps];
    }
    

    Working example: https://codesandbox.io/s/6l6v9p0qkr

    0 讨论(0)
  • 2020-11-27 10:32

    Here is a simplest way of implementing radio buttons in react js.

    class App extends React.Component {
      
      setGender(event) {
        console.log(event.target.value);
      }
      
      render() {
        return ( 
          <div onChange={this.setGender.bind(this)}>
            <input type="radio" value="MALE" name="gender"/> Male
            <input type="radio" value="FEMALE" name="gender"/> Female
          </div>
         )
      }
    }
    
    ReactDOM.render(<App/>, document.getElementById('app'));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
    <div id="app"></div>

    Edited

    You can use arrow function instead of binding. Replace the above code as

    <div onChange={event => this.setGender(event)}>

    For a default value use defaultChecked, like this

    <input type="radio" value="MALE" defaultChecked name="gender"/> Male
    
    0 讨论(0)
  • 2020-11-27 10:40
    import React, { Component } from "react";
    
    class RadionButtons extends Component {
      constructor(props) {
        super(props);
    
        this.state = {
          // gender : "" , // use this one if you don't wanna any default value for gender
          gender: "male" // we are using this state to store the value of the radio button and also use to display the active radio button
        };
    
        this.handleRadioChange = this.handleRadioChange.bind(this);  // we require access to the state of component so we have to bind our function 
      }
    
      // this function is called whenever you change the radion button 
      handleRadioChange(event) {
          // set the new value of checked radion button to state using setState function which is async funtion
        this.setState({
          gender: event.target.value
        });
      }
    
    
      render() {
        return (
          <div>
            <div check>
              <input
                type="radio"
                value="male" // this is te value which will be picked up after radio button change
                checked={this.state.gender === "male"} // when this is true it show the male radio button in checked 
                onChange={this.handleRadioChange} // whenever it changes from checked to uncheck or via-versa it goes to the handleRadioChange function
              />
              <span
               style={{ marginLeft: "5px" }} // inline style in reactjs 
              >Male</span>
            </div>
            <div check>
              <input
                type="radio"
                value="female"
                checked={this.state.gender === "female"}
                onChange={this.handleRadioChange}
              />
              <span style={{ marginLeft: "5px" }}>Female</span>
            </div>
          </div>
        );
      }
    }
    export default RadionButtons;
    
    0 讨论(0)
提交回复
热议问题