如何检索单选按钮选择的值和名称。我使用了selectedOption,它只检索值。谢谢。 App.js
const tuitions=[
{name:"In-state Resident", tuition: 1000, key:1 },
{name:"Out-state Resident",tuition: 2000, key: 2}
];
class App extends Component {
constructor(props){
super(props);
this.state={
};
}
_RadioClickHandler=(event)=>{
this.setState({
selectedOption:event.target.value
})
}
render() {
return (
<div className="App">
<form>
{tuitions.map(item=>(
<RadioGroup
value={item.value}
key={item.key}
name={item.name}
onChange={this._RadioClickHandler.bind(this)}
/>)
)}
<p>Display
<InstitutionList
selectedList={this.state.selectedList}
resident={this.state.selectedOption}
/>
</p>
// this.state.selectedOption仅传递值
RadioGroup.js
import React from 'react';
const radioGroup=(props)=>{
return (
<div>
<input
type="radio"
name="School"
value={props.value}
onChange={props.onChange}
/>
{props.name}
</div>
);
}
export default radioGroup;
答案 0 :(得分:0)
您可以将其传递给变更处理程序,如下所示:
onChange={e => this._RadioClickHandler (e, item.name) }
看看下面的代码片段,看看它可以正常工作:
const tuitions = [
{ value: 'ValueA', key: 'KeyA', name: 'Name A' },
{ value: 'ValueB', key: 'KeyB', name: 'Name B' },
{ value: 'ValueC', key: 'KeyC', name: 'Name C' }
];
const RadioButton = (props) => (
<label>
<input
type="radio"
name="Schools"
value={props.value}
onChange={props.onChange}
/>
{props.name}
</label>
);
class Thingy extends React.Component {
_RadioClickHandler = (e, name) => {
alert(`Value:${e.target.value}, Name:${name}`);
}
render() {
return (
<div>
{tuitions.map(item=>(
<RadioButton
value={item.value}
key={item.key}
name={item.name}
onChange={e => this._RadioClickHandler (e, item.name) }
/>
)
)}
</div>
);
}
}
// Render it
ReactDOM.render(
<Thingy />,
document.body
);
<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>