如何在ReactJS中使用单选按钮?

时间:2015-01-05 16:55:29

标签: html reactjs

我是ReactJS的新手,如果这听起来很对不起。我有一个组件,根据收到的数据创建几个表行。

列中的每个单元格都有一个单选复选框。因此,用户可以从现有行中选择一个site_name和一个address。选择应显示在页脚中。那就是我被困住的地方。

var SearchResult = React.createClass({
   render: function(){
       var resultRows = this.props.data.map(function(result){
           return (
               <tbody>
                    <tr>
                        <td><input type="radio" name="site_name" value={result.SITE_NAME}>{result.SITE_NAME}</input></td>
                        <td><input type="radio" name="address" value={result.ADDRESS}>{result.ADDRESS}</input></td>
                    </tr>
               </tbody>
           );
       });
       return (
           <table className="table">
               <thead>
                   <tr>
                       <th>Name</th>
                       <th>Address</th>
                   </tr>
               </thead>
                {resultRows}
               <tfoot>
                   <tr>
                       <td>chosen site name ???? </td>
                       <td>chosen address ????? </td>
                   </tr>
               </tfoot>
           </table>
       );
   }
});

在jQuery中我可以执行$("input[name=site_name]:checked").val()之类的操作来选择一个单选复选框类型并将其插入到第一个页脚单元格中。

但肯定有一种Reactjs方式,我完全不知道了吗?非常感谢

13 个答案:

答案 0 :(得分:162)

对渲染的任何更改都应通过statepropsreact doc)进行更改。

所以在这里我注册输入事件,然后更改state,然后触发渲染显示在页脚上。

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

答案 1 :(得分:81)

这是在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>

<强>被修改

您可以使用箭头功能而不是绑定。将上面的代码替换为

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

对于默认值,使用defaultChecked,就像这样

<input type="radio" value="MALE" defaultChecked name="gender"/> Male

答案 2 :(得分:16)

将无线电组件设为哑组件,并将道具传递给父组件。

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;

答案 3 :(得分:13)

基于React Docs say

  

处理多项输入。   当您需要处理多个受控输入元素时,可以为每个元素添加一个name属性,并让处理函数根据event.target.name的值选择要执行的操作。

例如:

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

链接到示例:https://codesandbox.io/s/6l6v9p0qkr

首先,没有选择任何单选按钮,因此this.state是一个空对象,但每当选择单选按钮时,this.state会获得一个带有输入名称及其值的新属性。然后,它会轻松检查用户是否选择了以下任何单选按钮:

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

修改

对于React的16.7-alpha版本is a proposalhooks可以让你更轻松地完成这些工作:

在下面的示例中,功能组件中有两组单选按钮。他们仍然控制着投入:

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];
}

工作示例:https://codesandbox.io/s/6l6v9p0qkr

答案 4 :(得分:7)

这里只是一个想法:当谈到React中的无线电输入时,我通常会以前面答案中提到的不同方式呈现所有这些。

如果这可以帮助任何需要渲染大量单选按钮的人:

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>

答案 5 :(得分:4)

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;

答案 6 :(得分:2)

单击单选按钮应触发以下任一事件:

  1. 调用setState,如果您只希望选择知识是本地的,或
  2. 调用从上面self.props.selectionChanged(...)
  3. 传入的回调

    在第一种情况下,更改状态将触发重新渲染,您可以执行
    <td>chosen site name {this.state.chosenSiteName} </td>

    在第二种情况下,回调的来源将更新事物以确保在线下,你的SearchResult实例将在其道具中设置selectedSiteName和selectedAddress。

答案 7 :(得分:2)

我也在电台,复选框实施方面感到困惑。我们需要的是,收听收音机的更改事件,然后设置状态。我做了一个性别选择的小例子。

/*
 * 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>

答案 8 :(得分:2)

引导家伙,我们这样做:


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>
        </>
    )
}

答案 9 :(得分:2)

这是我用过的。希望这会有所帮助。
先定义变量。

const [variableName, setVariableName] = useState("");

然后,我们将需要实际的单选按钮。

<input
   type="radio"
   name="variableName"
   value="variableToCheck"
   onChange={(e) =>
   setVariableName("variableToCheck")
   }
   checked={variableName === "variableToCheck"}
/>

答案 10 :(得分:1)

在ChinKang的基础上建议他回答说,对于那些感兴趣的人,我有更干的方法和es6:

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>
    )
  }
}

除了这个将具有默认的选中值。

答案 11 :(得分:0)

@Tomasz Mularczyk 在他的回答中提到了 react 钩子,但我想我已经提出了一个我最近使用的仅使用 If Not Intersect(Target, Range("A1:B1")) Is Nothing Then With Range("A1") .Value = Now() .NumberFormat = "mm/dd/yyyy h:mm:ss AM/PM" End With With Range("B1") .Value = Now() .NumberFormat = "mm/dd/yyyy h:mm:ss AM/PM" End With End If 钩子的解决方案。

useState

答案 12 :(得分:0)

import React from 'react';
import './style.css';

export default function App() {
  const [currentRadioValue, setCurrentValue] = React.useState('on');
  const handleRadioChange = value => {
    setCurrentValue(value);
  };
  return (
    <div>
      <>
        <div>
          <input
            name="radio-item-1"
            value="on"
            type="radio"
            onChange={e => setCurrentValue(e.target.value)}
            defaultChecked={currentRadioValue === 'on'}
          />
          <label htmlFor="radio-item-1">Radio Item 1</label>
          {currentRadioValue === 'on' && <div>one</div>}
        </div>
        <div>
          <input
            name="radio-item-1"
            value="off"
            type="radio"
            onChange={e => setCurrentValue(e.target.value)}
            defaultChecked={currentRadioValue === 'off'}
          />
          <label htmlFor="radio-item-2">Radio Item 2</label>
          {currentRadioValue === 'off' && <div>two</div>}
        </div>
      </>
    </div>
  );
}

工作示例:https://stackblitz.com/edit/react-ovnv2b