我正在開發一個簡單的民意調查,以此作爲我在reactjs上發展的方式。到目前爲止,我想出了以下幾點: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)
我想要單擊按鈕時獲取單選按鈕的值。
在localhost和jsfiddle上的相同代碼https://jsfiddle.net/69z2wepo/91274/當單選按鈕被選中時我可以在控制檯中看到狀態,但單選按鈕沒有被檢查,爲什麼? – jwesonga
請注意,我將json選項值更改爲字符串。元素值將被轉換爲字符串。所以如果沒有這種改變,你的'checked = {selected === choice.value}'會比較''1'=== 1'這是錯誤的。你可以使用double equals(比如'selected == choice.value',但是更好的做法是'selected === choice.value.toString()' –