How to use radio buttons in ReactJS?

前端 未结 10 2093
再見小時候
再見小時候 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:16

    Make the radio component as dumb component and pass props to from parent.

    import React from "react";
    
    const Radiocomponent = ({ value, setGender }) => ( 
      <div onChange={setGender.bind(this)}>
        <input type="radio" value="MALE" name="gender" defaultChecked={value ==="MALE"} /> Male
        <input type="radio" value="FEMALE" name="gender" defaultChecked={value ==="FEMALE"}/> Female
      </div>
    );
    
    export default Radiocomponent;
    
    0 讨论(0)
  • 2020-11-27 10:17

    Clicking a radio button should trigger an event that either:

    1. calls setState, if you only want the selection knowledge to be local, or
    2. calls a callback that has been passed in from above self.props.selectionChanged(...)

    In the first case, the change is state will trigger a re-render and you can do
    <td>chosen site name {this.state.chosenSiteName} </td>

    in the second case, the source of the callback will update things to ensure that down the line, your SearchResult instance will have chosenSiteName and chosenAddress set in it's props.

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

    Bootstrap guys, we do it like this:

    
    export default function RadioButton({ onChange, option }) {
        const handleChange = event => {
            onChange(event.target.value)
        }
    
        return (
            <>
                <div className="custom-control custom-radio">
                    <input
                        type="radio"
                        id={ option.option }
                        name="customRadio"
                        className="custom-control-input"
                        onChange={ handleChange }
                        value = { option.id }
                        />
                        <label
                            className="custom-control-label"
                            htmlFor={ option.option }
                            >
                            { option.option }
                        </label>
                </div>
            </>
        )
    }
    
    
    0 讨论(0)
  • 2020-11-27 10:26

    To build upon ChinKang said for his answer, I have a more dry'er approach and in es6 for those interested:

    class RadioExample extends React.Component {
      constructor(props) {
        super(props);
    
        this.state = {
          selectedRadio: 'public'
        };
      }
    
      handleRadioChange = (event) => {
        this.setState({
          selectedRadio: event.currentTarget.value
        })
      };
    
      render() {
        return (
          <div className="radio-row">
            <div className="input-row">
              <input
                type="radio"
                name="public"
                value="public"
                checked={this.state.selectedRadio === 'public'}
                onChange={this.handleRadioChange}
              />
              <label htmlFor="public">Public</label>
            </div>
            <div className="input-row">
              <input
                type="radio"
                name="private"
                value="private"
                checked={this.state.selectedRadio === 'private'}
                onChange={this.handleRadioChange}
              />
              <label htmlFor="private">Private</label>
            </div>
          </div>
        )
      }
    }
    

    except this one would have a default checked value.

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

    I also got confused in radio, checkbox implementation. What we need is, listen change event of the radio, and then set the state. I have made small example of gender selection.

    /*
     * A simple React component
     */
    class App extends React.Component {
      constructor(params) {
         super(params) 
         // initial gender state set from props
         this.state = {
           gender: this.props.gender
         }
         this.setGender = this.setGender.bind(this)
      }
      
      setGender(e) {
        this.setState({
          gender: e.target.value
        })
      }
      
      render() {
        const {gender} = this.state
        return  <div>
            Gender:
            <div>
              <input type="radio" checked={gender == "male"} 
    onClick={this.setGender} value="male" /> Male
              <input type="radio" checked={gender == "female"} 
    onClick={this.setGender} value="female"  /> Female
            </div>
            { "Select Gender: " } {gender}
          </div>;
      }
    }
    
    /*
     * Render the above component into the div#app
     */
    ReactDOM.render(<App gender="male" />, 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>

    0 讨论(0)
  • Any changes to the rendering should be change via the state or props (react doc).

    So here I register the event of the input, and then change the state, which will then trigger the render to show on the footer.

    var SearchResult = React.createClass({
      getInitialState: function () {
        return {
          site: '',
          address: ''
        };
      },
      onSiteChanged: function (e) {
        this.setState({
          site: e.currentTarget.value
          });
      },
    
      onAddressChanged: function (e) {
        this.setState({
          address: e.currentTarget.value
          });
      },
    
      render: function(){
           var resultRows = this.props.data.map(function(result){
               return (
                   <tbody>
                        <tr>
                            <td><input type="radio" name="site_name" 
                                       value={result.SITE_NAME} 
                                       checked={this.state.site === result.SITE_NAME} 
                                       onChange={this.onSiteChanged} />{result.SITE_NAME}</td>
                            <td><input type="radio" name="address" 
                                       value={result.ADDRESS}  
                                       checked={this.state.address === result.ADDRESS} 
                                       onChange={this.onAddressChanged} />{result.ADDRESS}</td>
                        </tr>
                   </tbody>
               );
           }, this);
           return (
               <table className="table">
                   <thead>
                       <tr>
                           <th>Name</th>
                           <th>Address</th>
                       </tr>
                   </thead>
                    {resultRows}
                   <tfoot>
                       <tr>
                           <td>chosen site name {this.state.site} </td>
                           <td>chosen address {this.state.address} </td>
                       </tr>
                   </tfoot>
               </table>
           );
      }
    });
    

    jsbin

    0 讨论(0)
提交回复
热议问题