gpt4 book ai didi

javascript - 仅打印单击的单选按钮值(React)

转载 作者:行者123 更新时间:2023-12-01 01:48:40 25 4
gpt4 key购买 nike

在控制台中打印选定的单选按钮值。如果所有 radio 组均已应答,则仅在控制台中打印 selected= true radioValue。例如:如果 NO radiobutton= true,则其值为 2。它应该打印值 2。就像所有 true radiovalue 都应该在控制台中打印。
谢谢

//array of cards coming from the backend
const data = [
{
cardName: 'Do you want sugar in your coffee',
options: [
{ radioName: 'Yes',radioValue: '1', selected: false },
{ radioName: 'No',radioValue: '2', selected: false }]
},
{
cardName: 'Do you want milk in your coffee',
options: [
{ radioName: 'Yes',radioValue: '1', selected: false },
{ radioName: 'No',radioValue: '2', selected: false }]
},
{
cardName: 'Do you want low-fat-milk in your coffee',
options: [
{ radioName: 'Yes',radioValue: '1', selected: false },
{ radioName: 'No',radioValue: '2', selected: false }]
}
];


class CardsList extends React.Component {
constructor(props) {
super(props);
this.state = {
cards: [],

};
}

componentDidMount() {
setTimeout(() => {
// mimic an async server call
this.setState({ cards: data });
}, 1000);
}

onInputChange = ({ target }) => {
const { cards } = this.state;
const nexState = cards.map(card => {
if (card.cardName !== target.name) return card;
return {
...card,
options: card.options.map(opt => {
const checked = opt.radioName === target.value;
return {
...opt,
selected: checked
}
})
}
});
this.setState({ cards: nexState })
}

onSubmit = () => {
console.log(this.state.cards.map(({ cardName, options }) => {
const option = options.filter(({ selected }) => selected)[0]
return ` ${option.radioValue}`
}))
};

onReset = () => {
this.setState({cards:[]});
}
render() {
const { cards } = this.state;
return (
<div>
{
cards.length < 1 ? "Loading..." :
<div>
{cards.map((card, idx) => (
<ul>
{card.cardName}
{card.options.radioName}

{
card.options.map((lo, idx) => {
return <input
key={idx}
type="radio"
name={card.cardName}
value={lo.radioName}
checked={!!lo.selected}
onChange={this.onInputChange}
/>

})
}
</ul>
))
}
< button onClick={this.onSubmit}>Submit</button>
< button onClick={this.onReset}>Clear</button>
</div>
}

</div>
);
}
}

ReactDOM.render(<CardsList />, document.getElementById('root'));
<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>

最佳答案

onSubmit 中的登录更改为此

console.log(this.state.cards.map(({ cardName, options }) => {
const option = options.filter(({ selected }) => selected)[0]
return `${cardName}: ${option.radioName}`
}))

通过这种方式,您可以将选项过滤到 selected 为 true 的选项,并选择第一个。

要解决您的第一个问题,只需在执行日志之前映射 this.state.cards 数组并检查是否正好有 1 个 option,其中 选择 为真。如果情况并非如此,请以您想要的任何方式告诉用户。

您还可以删除构造函数并将其更改为:

state = {
cards: [],
}

因为你没有在构造函数中访问你的 props

关于javascript - 仅打印单击的单选按钮值(React),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51760329/

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