Html 如何在 ReactJS 中使用单选按钮?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27784212/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use radio buttons in ReactJS?
提问by Houman
I am new to ReactJS, sorry if this sounds off. I have a component that creates several table rows according to the received data.
我是 ReactJS 的新手,如果这听起来不对,抱歉。我有一个组件可以根据接收到的数据创建多个表行。
Each cell within the column has a radio checkbox. Hence the user can select one site_name
and one address
from the existing rows. The selection shall be shown in the footer. And thats where I am stuck.
列中的每个单元格都有一个单选框。因此,用户可以从现有行中选择一个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>
);
}
});
In jQuery I could do something like $("input[name=site_name]:checked").val()
to get the selection of one radio checkbox type and insert it into the first footer cell.
在 jQuery 中,我可以做一些事情,比如$("input[name=site_name]:checked").val()
选择一个单选复选框类型并将其插入到第一个页脚单元格中。
But surely there must be a Reactjs way, which I am totally missing? Many Thanks
但肯定必须有一种 Reactjs 方式,我完全想念它吗?非常感谢
回答by ChinKang
Any changes to the rendering should be change via the state
or props
(react doc).
对渲染的任何更改都应该通过state
或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.
所以在这里我注册输入的事件,然后更改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>
);
}
});
回答by Saahithyan Vigneswaran
Here is a simplest way of implementing radio buttons in react js.
这是在 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)}>
<div onChange={event => this.setGender(event)}>
For a default value use defaultChecked
, like this
对于默认值使用defaultChecked
,像这样
<input type="radio" value="MALE" defaultChecked name="gender"/> Male
回答by Tomasz Mularczyk
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.
处理多个输入。当需要处理多个受控输入元素时,可以给每个元素添加一个name属性,让处理函数根据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
示例链接: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:
起初,没有一个单选按钮被选中,所以this.state
是一个空对象,但是每当单选按钮被选中时,this.state
都会获得一个带有输入名称及其值的新属性。然后可以轻松检查用户是否选择了任何单选按钮,例如:
const isSelected = this.state.platform ? true : false;
EDIT:
编辑:
With version 16.7-alpha of React there is a proposalfor something called hooks
which will let you do this kind of stuff easier:
在 React 的 16.7-alpha 版本中,有一个名为的提议,hooks
它可以让您更轻松地完成此类工作:
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
回答by Khalid Azam
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;
回答by Arnaud
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.
这里只是一个想法:当谈到 React 中的无线电输入时,我通常以不同的方式呈现它们,这在之前的答案中提到过。
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>
回答by ABHIJEET KHIRE
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;
回答by Tony Tai Nguyen
To build upon ChinKang said for his answer, I have a more dry'er approach and in es6 for those interested:
为了建立在 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>
)
}
}
except this one would have a default checked value.
除了这个会有一个默认的检查值。
回答by z5h
Clicking a radio button should trigger an event that either:
单击单选按钮应触发以下事件之一:
- calls setState, if you only want the selection knowledge to be local, or
- calls a callback that has been passed in from above
self.props.selectionChanged(...)
- 调用 setState,如果您只希望选择知识是本地的,或者
- 调用从上面传入的回调
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>
在第一种情况下,更改状态将触发重新渲染,您可以这样做<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.
在第二种情况下,回调的源将更新内容以确保您的 SearchResult 实例将在其道具中设置 selectedSiteName 和 selectedAddress 。
回答by rab
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>
回答by GilbertS
Bootstrap guys, we do it like this:
Bootstrap 伙计们,我们这样做:
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>
</>
)
}