仅打印单击的单选按钮值(反应)

时间:2018-08-09 06:38:21

标签: javascript arrays reactjs javascript-objects radio-group

在控制台中打印选定的单选按钮值。 如果回答了所有单选组,则仅在控制台中打印选定的= 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>

2 个答案:

答案 0 :(得分:1)

onSubmit中的日志更改为此

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

通过这种方式,您可以将选项过滤为selected为真的选项,然后选择第一个。

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

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

state = {
    cards: [],
}

因为您没有在构造函数中访问道具

答案 1 :(得分:1)

您可以回答@george,

要检查每个卡是否单击了单选按钮,可以运行验证检查

let unselectedCards = this.state.cards.filter((card) => {
   return !card.options[0].selected && !card.options[1].selected
});

使用unselectedCards变量突出显示卡片。

如果您有更多选择,可以在卡片地图内再次使用地图选项。