Reactjs:获取单选按钮的值

4

我正在开发一个简单的意见调查网站来学习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)

我希望你能在单选按钮点击时获取其值。
2个回答

5

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

同样的代码在本地主机和jsfiddle上 https://jsfiddle.net/69z2wepo/91274/ 当单选按钮被选中时,我可以在控制台中看到状态,但是单选按钮没有被选中,为什么会这样? - jwesonga
请注意,我将json选项值更改为字符串。元素值将被转换为字符串。因此,如果没有这个更改,您的 checked={selected === choice.value} 将会比较 '1' === 1,这是错误的。您可以使用双等号 selected == choice.value,但最好使用 selected === choice.value.toString() - Rick Jolly
注意:将index设置为key是一种反模式!会导致不可预测的结果。 - Alexey Nikonov

2

PollOption是一个功能组件,因此this关键字对其不可访问,所以onChange={() => this.props.onChange()}将无法工作。此外,您需要将所选值传递给父级。

正如@RickyJolly在评论中提到的那样,您需要为onChange添加checked属性才能触发它。

const PollOption = ({options, onChange, selectedValue}) => {
  return (
    <div className="pollOption">
      {options.map((choice, index) => (
        <label key={index}>
        <input type="radio" 
                name="vote" 
                value={choice.value} 
                key={index}
                checked={selectedValue === choice.value}
                onChange={(e) => onChange(e.target.value)}/>
                {choice.text}
        </label>
      ))}  
    </div>
   );
};

class OpinionPoll extends Component{
  constructor(props) {
    super(props);
    this.state = {selectedOption: ''}
  }

  handleClick(){
    console.log('button clicked');
  }

  handleOnChange(val){
    console.log('foo', val);
  }

  render(){
    return (
      <div className="poll">
        {this.props.model.question}
        <PollOption 
          options={this.props.model.choices}
          onChange={(val) => this.handleOnChange(val)}
          selectedValue={this.state.selectedOption}
       />

        <button onClick={() => this.handleClick()}>Vote!</button>
      </div>
    );
  }
}

回答不错,但有一个小问题是onChange事件不会触发,因为单选按钮没有被选中的属性发生变化,因此它不会注册更改。 - Rick Jolly
谢谢,之前没有太注意。已更新答案。 - Shubham Khatri

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接