我正在开发一个简单的意见调查网站来学习reactjs。到目前为止,我已经想到了以下内容:
//App.js
import React, { Component } from 'react';
import './App.css';
const PollOption = ({options}) => {
return (
<div className="pollOption">
{options.map((choice, index) => (
<label key={index}>
<input type="radio"
name="vote"
value={choice.value}
key={index}
defaultChecked={choice.value}
onChange={() => this.props.onChange()}/>
{choice.text}
</label>
))}
</div>
);
};
class OpinionPoll extends Component{
constructor(props) {
super(props);
this.state = {selectedOption: ''}
}
handleClick(){
console.log('button clicked');
}
handleOnChange(){
console.log('foo');
}
render(){
return (
<div className="poll">
{this.props.model.question}
<PollOption
options={this.props.model.choices}
onChange={() => this.handleOnChange()}/>
<button onClick={() => this.handleClick()}>Vote!</button>
</div>
);
}
}
export default OpinionPoll;
//index.js
var json = {
question: 'Do you support cookies in cakes?',
choices:
[
{text: "Yes", value: 1},
{text: "No", value: 2}
]
}
const root = document.getElementById("root");
render(<OpinionPoll model ={json} />, root)
我希望你能在单选按钮点击时获取其值。
checked={selected === choice.value}
将会比较'1' === 1
,这是错误的。您可以使用双等号selected == choice.value
,但最好使用selected === choice.value.toString()
。 - Rick Jolly