gpt4 book ai didi

Reactjs:获取单选按钮的值

转载 作者:行者123 更新时间:2023-12-04 03:03:10 25 4
gpt4 key购买 nike

我正在开发一个简单的民意调查作为我提高 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)

我想在单击按钮时获取单选按钮的值。

最佳答案

只需对@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'));

关于Reactjs:获取单选按钮的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47234497/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com