最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React radio buttons update state - Stack Overflow

programmeradmin2浏览0评论

I have a problem with implementing the radio buttons ponent in my React App. I have a json file, with different options, like this:

[ 
"food": [
   {
    "id": 1,
    "name": "Pizza",
    "options": [
        {
            "id": 11,
            "name": "Margherita",
        },
        {
            "id": 12,
            "name": "Pepperoni",
        },
        {
            "id": 13,
            "name": "Prosciutto",
        },
        {
            "id": 14,
            "name": "Prataiolo",
        }
    ]
  },
  {
    "id": 2,
    "name": "Size",
    "options": [
        {
            "id": 21,
            "name": "S",
        },
        {
            "id": 22,
            "name": "M",
        },
        {
            "id": 23,
            "name": "L",
        },
        {
            "id": 24,
            "name": "XL",
        },
    ]
 }

I want to make a radio buttons, for the user to choose the pizza they want and put it in the ponent state.

How can I make this work with two groups of radio buttons?

class PizzaList extends Component{
  constructor(props){
  super(props);
    this.state = {
        pizza: '',
        size: ''
     }

  render(){

  return(
    {this.props.food.map(option => {
      <h2 key={option.id}>{option.name}</h2>
        {option.options.map(value => {
          <input 
            type='radio'
            value='value.id'
           />
        })
     })}
   )
 }

I have a problem with implementing the radio buttons ponent in my React App. I have a json file, with different options, like this:

[ 
"food": [
   {
    "id": 1,
    "name": "Pizza",
    "options": [
        {
            "id": 11,
            "name": "Margherita",
        },
        {
            "id": 12,
            "name": "Pepperoni",
        },
        {
            "id": 13,
            "name": "Prosciutto",
        },
        {
            "id": 14,
            "name": "Prataiolo",
        }
    ]
  },
  {
    "id": 2,
    "name": "Size",
    "options": [
        {
            "id": 21,
            "name": "S",
        },
        {
            "id": 22,
            "name": "M",
        },
        {
            "id": 23,
            "name": "L",
        },
        {
            "id": 24,
            "name": "XL",
        },
    ]
 }

I want to make a radio buttons, for the user to choose the pizza they want and put it in the ponent state.

How can I make this work with two groups of radio buttons?

class PizzaList extends Component{
  constructor(props){
  super(props);
    this.state = {
        pizza: '',
        size: ''
     }

  render(){

  return(
    {this.props.food.map(option => {
      <h2 key={option.id}>{option.name}</h2>
        {option.options.map(value => {
          <input 
            type='radio'
            value='value.id'
           />
        })
     })}
   )
 }
Share Improve this question edited Jun 1, 2020 at 12:45 Treycos 7,4923 gold badges28 silver badges51 bronze badges asked Jan 18, 2019 at 12:27 AndrewAndrew 1491 gold badge6 silver badges12 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

The main problem in your mapping is that your forgot to return any value. you can either add a return statement, or simply delete the brackets.

You also need to set the name of each button to be sure that the user may only select one at a time.

Now, to handle changes you will need to set the value of each input to the field name and bind it to a change function that will send out the name it belongs to :

<input
    type='radio'
    value={this.state[name]}
    name={name}
    key={opt.id}
    onChange={this.selectionChanged(name)}
/>

And the change handling function :

selectionChanged = type => ev => {
    this.setState({ [type]: ev.target.value })
    console.log('Selection of ' + type ' changed to ' + ev.target.value)
}

Working example :

const data = {
    "food": [
        {
            "id": 1,
            "name": "Pizza",
            "options": [
                {
                    "id": 11,
                    "name": "Margherita",
                },
                {
                    "id": 12,
                    "name": "Pepperoni",
                },
                {
                    "id": 13,
                    "name": "Prosciutto",
                },
                {
                    "id": 14,
                    "name": "Prataiolo",
                }
            ]
        },
        {
            "id": 2,
            "name": "Size",
            "options": [
                {
                    "id": 21,
                    "name": "S",
                },
                {
                    "id": 22,
                    "name": "M",
                },
                {
                    "id": 23,
                    "name": "L",
                },
                {
                    "id": 24,
                    "name": "XL",
                },
            ]
        }
    ]
}

class PizzaList extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            Pizza: '',
            Size: ''
        }
    }

    selectionChanged = type => ev => {
        this.setState({ [type]: ev.target.value })
        console.log('Selection of ' + type + ' changed to ' + ev.target.value)
    }

    render() {
        return (
            <div>
                {this.props.food.map(({ id, name, options }) =>
                    <div key={id}>
                        <h2>{name}</h2>
                        {options.map((opt) =>
                            <input
                                type='radio'
                                value={opt.name}
                                name={name}
                                key={opt.id}
                                onChange={this.selectionChanged(name)}
                            />
                        )}
                    </div>
                )}
            </div>
        )
    }
}

ReactDOM.render(<PizzaList food={data.food}/>, document.getElementById('root'))
<script src="https://cdnjs.cloudflare./ajax/libs/react/16.5.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/react-dom/16.5.1/umd/react-dom.production.min.js"></script>
<div id='root'/>

This is how you could define two set of radio group buttons, within one form element.

<form>
<fieldset id="group1">
<input type="radio" value="value1" name="group1" onChange={this.handleChangea}>
<input type="radio" value="value2" name="group1" onChange={this.handleChangea}>
</fieldset>

<fieldset id="group2">
<input type="radio" value="value1" name="group2" onChange={this.handleChangeb}>
<input type="radio" value="value2" name="group2" onChange={this.handleChangeb}>
<input type="radio" value="value3" name="group2" onChange={this.handleChangeb}>
</fieldset>
</form>

To set the state, Simply, write this in handlechange method.

handleChange=(event)=> {
    console.log(event.target.value);
    this.setState({
      selectedoptionId : event.target.value
    })
    tempobj["optionId"] = event.target.value
  };

About this tempobj["optionId"] = event.target.value , Since you are iteratively adding the form ponent, you will need to save the answers, such that we don't lose the previous set of answers. For this I save the options in a JSON object itself. with OptionID as key and answers in respective JSON values. I could give a more detailed answer o how I am saving these values, but only if you need it.

发布评论

评论列表(0)

  1. 暂无评论