我正在制定一项简单的民意调查,作为我加强反应的方式。到目前为止,我已经提出以下建议:
//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)
我希望在单击按钮时获得单选按钮的值。
答案 0 :(得分:2)
只需稍微修改@Shubham Khatri答案即可添加checked
属性和选定状态。在这里演示:https://codesandbox.io/s/vqz25ov285
const json = {
question: 'Do you support cookies in cakes?',
choices:
[
{ text: 'Yes', value: '1' },
{ text: 'No', value: '2' }
]
}
const PollOption = ({ options, selected, onChange }) => {
return (
<div className="pollOption">
{options.map((choice, index) => (
<label key={index}>
<input type="radio"
name="vote"
value={choice.value}
key={index}
checked={selected === choice.value}
onChange={onChange} />
{choice.text}
</label>
))}
</div>
);
};
class OpinionPoll extends React.Component {
constructor(props) {
super(props);
this.state = { selectedOption: '' }
}
handleClick() {
console.log('submitted option', this.state.selectedOption);
}
handleOnChange(e) {
console.log('selected option', e.target.value);
this.setState({ selectedOption: e.target.value});
}
render() {
return (
<div className="poll">
{this.props.model.question}
<PollOption
options={this.props.model.choices}
onChange={(e) => this.handleOnChange(e)}
selected={this.state.selectedOption} />
<button onClick={() => this.handleClick()}>Vote!</button>
</div>
);
}
}
render(<OpinionPoll model={json} />, document.getElementById('root'));
答案 1 :(得分:1)
PollOption是一个功能组件,因此this
关键字不可访问,因此onChange={() => this.props.onChange()}
不起作用。您还需要将所选值传递给父级。
同样@RickyJolly在评论中提到,您需要触发checked
的{{1}}属性。
onChange