如何仅使用React获取选中的单选按钮值?

时间:2016-12-04 10:41:58

标签: reactjs radio-button

我一直在搜索stackoverflow(和其他地方)已经很久了,但似乎无法找到我的问题的任何解决方案(或者至少没有我理解的并且可以应用于我的代码......)。

我们有一份学校作业,我们只允许使用React。我正在使用单选按钮,并希望显示已选中的单选按钮,但我不明白应该如何完成。

我会在没有很多不同测试的情况下粘贴我的原始代码,我知道这不起作用,但我不明白我应该添加什么。使用原始代码我只得到“5”,这是单选按钮组中的最后一个值,无论我选择检查什么。

谢谢!

//Displaying value
render: function render() {
  return React.createElement(
    "div",
    { className: "hotelRating" },
    React.createElement(
      "p",
      { className: "rating" },
      this.props.rating
    )
  );
}

//Displaying the form
render: function render() {
  return React.createElement(
    "form",
    { onSubmit: this.handleSubmit },
    React.createElement("input", { className: "rating-input", type: "radio", name: "rate", value: "1", ref: "rating" }),
    React.createElement("input", { className: "rating-input", type: "radio", name: "rate", value: "2", ref: "rating" }),
    React.createElement("input", { className: "rating-input", type: "radio", name: "rate", value: "3", ref: "rating" }),
    React.createElement("input", { className: "rating-input", type: "radio", name: "rate", value: "4", ref: "rating" }),
    React.createElement("input", { className: "rating-input", type: "radio", name: "rate", value: "5", ref: "rating" }),
    React.createElement("button",{ href: true, id: "add" }, "Add rating")
  );
}

更新: 因为我被要求粘贴我的整个代码,所以就这样了。 正如您所看到的,我正在尝试使用反应来建立一个酒店数据库。我还没有完成所有部件,所以我知道这不仅仅是评级不起作用。我也在努力为帖子添加“编辑”功能:)

<!doctype html>
<html>
    <head>
        <title>Assignment 5</title>
        <meta charset="utf-8">
        <script src="js/react.min.js"></script>
        <script src="js/react-dom.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
        <link rel="stylesheet" href="css/styles.css" />
    </head>
    <body>
		<div id="hotelsDB"></div>
		<script>
			"use strict";
			var HotelEntry = React.createClass({
				remove: function remove(event) {
					event.preventDefault();
					event.stopPropagation();
					this.props.onUpdate({ remove: true });
				},
				render: function render() {
					return React.createElement(
						"div", {
							className: "hotelEntry"
						},
						React.createElement(
							"h2", {
								className: "hotelName"
							},
							this.props.hotelName
						),
						React.createElement(
							"p",{
								className: "rating" 
							},
							this.props.rating
						),
						React.createElement(
							"p", {
								className: "addressLine"
							},
							React.createElement(
								"span", {
									className: "bold"
								},
								"Address: "
							),
							this.props.address	
						),
						React.createElement(
							"p", {
								className: "website bold"
							}, 
							"Website: ",
							this.props.website && React.createElement(
								"a", {
									target: "_blank", href: this.props.website
								},
							this.props.website)
						),
						React.createElement(
							"div", {
								className: "buttons"
							},
							React.createElement(
								"a", {
									href: true, className: "edit", onClick: this.remove
								}	
							),
							React.createElement(
								"a", {
									href: true, className: "remove", onClick: this.remove
								}
							)
						)
					);
				}
			});

			var Form = React.createClass({
				handleSubmit: function handleSubmit(event) {
					event.preventDefault();
					var hotelNode = ReactDOM.findDOMNode(this.refs.hotelName);
					var addressNode = ReactDOM.findDOMNode(this.refs.address);
					var websiteNode = ReactDOM.findDOMNode(this.refs.website);
					var ratingNode = ReactDOM.findDOMNode(this.refs.rating);
					if (hotelNode.value != "") {
						this.props.onItemAdded({
							hotelName: hotelNode.value,
							address: addressNode.value,
							website: websiteNode.value,
							rating: ratingNode.value,
						});
						hotelNode.value = "";
						addressNode.value = "";
						websiteNode.value = "";
						ratingNode.value = "";
					} else {
						alert("You must add a hotel name");
					}
				},
				render: function render() {
					return React.createElement(
						"form", {
							onSubmit: this.handleSubmit
						},
						React.createElement(
							"input", {
								placeholder: "Hotel name", ref: "hotelName"
							}
						),
						React.createElement(
							"input", {
								placeholder: "Address", ref: "address"
							}
						),
						React.createElement(
							"input", {
								type: "url", placeholder: "Website", ref: "website"
							}
						),
						React.createElement(
							"input", {
								className: "rating-input", type: "radio", name: "rate", value: "1", ref: "rating", onChange: this.handleChange
							}
						),
						React.createElement(
							"input", {
								className: "rating-input", type: "radio", name: "rate", value: "2", ref: "rating", onChange: this.handleChange
							}
						),
						React.createElement(
							"input", {
								className: "rating-input", type: "radio", name: "rate", value: "3", ref: "rating", onChange: this.handleChange
							}
						),
						React.createElement(
							"input", {
								className: "rating-input", type: "radio", name: "rate", value: "4", ref: "rating", onChange: this.handleChange
							}
						),
						React.createElement(
							"input", {
								className: "rating-input", type: "radio", name: "rate", value: "5", ref: "rating", onChange: this.handleChange
							}
						),
						React.createElement(
							"button", {
								href: true, id: "add"
							}, 
							"Add hotel"
						)
					);
				}
			});

			var HotelsHeader = React.createClass({
				render: function render() {
					return React.createElement(
						"h1",
						null,
						"Hotels"
					);
				}
			});

			var HotelsStockholm = React.createClass({
				showHeader: function showHeader() {
					return React.createElement(HotelsHeader, null);
				},
				getInitialState: function getInitialState() {
					return {
						items: this.getItemsFromLocalStore()
					};
				},
				buildItemNode: function buildItemNode(item, index) {
					return React.createElement(HotelEntry, {
						key: index,
						hotelName: item.hotelName,
						address: item.address,
						website: item.website,
						rating: item.rating,
						onUpdate: this.updateHotelEntry.bind(this, index) 
					});
				},
				handleNewItem: function handleNewItem(item) {
					var newItems = this.state.items.concat([item]);
					this.setState({ items: newItems });
				},
				updateHotelEntry: function updateHotelEntry(index, action) {
					var items = this.state.items;
					if (action.remove) {
						items.splice(index, 1);
					}
					this.setState({ items: items });
				},
				getItemsFromLocalStore: function getItemsFromLocalStore() {
					if (localStorage.items) {
						return JSON.parse(localStorage.items);
					} else {
						return [];
					}
				},
				componentWillUpdate: function componentWillUpdate(nextProps, nextState) {
					localStorage.items = JSON.stringify(nextState.items);
				},
				render: function render() {
					return React.createElement(
						'div',
						null,
						this.showHeader(),
						React.createElement(Form, {
							onItemAdded: this.handleNewItem 
						}),
						React.createElement(
							"div", {
								id: "hotels"
							},
							this.state.items.map(this.buildItemNode)
						)
					);
				}
			});
			ReactDOM.render(React.createElement(HotelsStockholm, null), document.getElementById('hotelsDB'));
        </script>
    </body>
</html>

1 个答案:

答案 0 :(得分:0)

这是工作fiddle

检查此代码。我认为这可以解决你的问题。

更新findDOMNode refs可能无法提供radio的准确checked。因此,我们为state component保留rating值,该值由handleChange()函数更新,后者又触发radio输入的更改。

<!doctype html>
<html>
    <head>
        <title>Assignment 5</title>
        <meta charset="utf-8">
        <script src="js/react.min.js"></script>
        <script src="js/react-dom.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
        <link rel="stylesheet" href="css/styles.css" />
    </head>
    <body>
        <div id="hotelsDB"></div>
        <script>
                        "use strict";
            var HotelEntry = React.createClass({
                remove: function remove(event) {
                    event.preventDefault();
                    event.stopPropagation();
                    this.props.onUpdate({ remove: true });
                },
                render: function render() {
                    return React.createElement(
                        "div", {
                            className: "hotelEntry"
                        },
                        React.createElement(
                            "h2", {
                                className: "hotelName"
                            },
                            this.props.hotelName
                        ),
                        React.createElement(
                            "p",{
                                className: "rating" 
                            },
                            this.props.rating
                        ),
                        React.createElement(
                            "p", {
                                className: "addressLine"
                            },
                            React.createElement(
                                "span", {
                                    className: "bold"
                                },
                                "Address: "
                            ),
                            this.props.address  
                        ),
                        React.createElement(
                            "p", {
                                className: "website bold"
                            }, 
                            "Website: ",
                            this.props.website && React.createElement(
                                "a", {
                                    target: "_blank", href: this.props.website
                                },
                            this.props.website)
                        ),
                        React.createElement(
                            "div", {
                                className: "buttons"
                            },
                            React.createElement(
                                "a", {
                                    href: true, className: "edit", onClick: this.remove
                                }   
                            ),
                            React.createElement(
                                "a", {
                                    href: true, className: "remove", onClick: this.remove
                                }
                            )
                        )
                    );
                }
            });

            var Form = React.createClass({
        getInitialState: function(){
            return {
            rating: 1
          };
        },
                handleSubmit: function (event) {
                    event.preventDefault();
                    var hotelNode = ReactDOM.findDOMNode(this.refs.hotelName);
                    var addressNode = ReactDOM.findDOMNode(this.refs.address);
                    var websiteNode = ReactDOM.findDOMNode(this.refs.website);
                    var ratingNode = ReactDOM.findDOMNode(this.refs.rating);
                    if (hotelNode.value != "") {
                        this.props.onItemAdded({
                            hotelName: hotelNode.value,
                            address: addressNode.value,
                            website: websiteNode.value,
                            rating: this.state.rating//ratingNode.value,
                        });
                        hotelNode.value = "";
                        addressNode.value = "";
                        websiteNode.value = "";
                        ratingNode.value = "";
                    } else {
                        alert("You must add a hotel name");
                    }
                },
        handleChange: function(event){
            var currentRating = event.target.value.trim();
          this.setState({
            rating: currentRating   
          });
        },
                render: function render() {
                    return React.createElement(
                        "form", {
                            onSubmit: this.handleSubmit
                        },
                        React.createElement(
                            "input", {
                                placeholder: "Hotel name", ref: "hotelName"
                            }
                        ),
                        React.createElement(
                            "input", {
                                placeholder: "Address", ref: "address"
                            }
                        ),
                        React.createElement(
                            "input", {
                                type: "url", placeholder: "Website", ref: "website"
                            }
                        ),
                        React.createElement(
                            "input", {
                                className: "rating-input", type: "radio", name: "rate", value: "1", ref: "rating", onChange: this.handleChange
                            }
                        ),
                        React.createElement(
                            "input", {
                                className: "rating-input", type: "radio", name: "rate", value: "2", ref: "rating", onChange: this.handleChange
                            }
                        ),
                        React.createElement(
                            "input", {
                                className: "rating-input", type: "radio", name: "rate", value: "3", ref: "rating", onChange: this.handleChange
                            }
                        ),
                        React.createElement(
                            "input", {
                                className: "rating-input", type: "radio", name: "rate", value: "4", ref: "rating", onChange: this.handleChange
                            }
                        ),
                        React.createElement(
                            "input", {
                                className: "rating-input", type: "radio", name: "rate", value: "5", ref: "rating", onChange: this.handleChange
                            }
                        ),
                        React.createElement(
                            "button", {
                                href: true, id: "add"
                            }, 
                            "Add hotel"
                        )
                    );
                }
            });

            var HotelsHeader = React.createClass({
                render: function render() {
                    return React.createElement(
                        "h1",
                        null,
                        "Hotels"
                    );
                }
            });

            var HotelsStockholm = React.createClass({
                showHeader: function showHeader() {
                    return React.createElement(HotelsHeader, null);
                },
                getInitialState: function getInitialState() {
                    return {
                        items: this.getItemsFromLocalStore()
                    };
                },
                buildItemNode: function buildItemNode(item, index) {
                    return React.createElement(HotelEntry, {
                        key: index,
                        hotelName: item.hotelName,
                        address: item.address,
                        website: item.website,
                        rating: item.rating,
                        onUpdate: this.updateHotelEntry.bind(this, index) 
                    });
                },
                handleNewItem: function handleNewItem(item) {
                    var newItems = this.state.items.concat([item]);
                    this.setState({ items: newItems });
                },
                updateHotelEntry: function updateHotelEntry(index, action) {
                    var items = this.state.items;
                    if (action.remove) {
                        items.splice(index, 1);
                    }
                    this.setState({ items: items });
                },
                getItemsFromLocalStore: function getItemsFromLocalStore() {
                    if (localStorage.items) {
                        return JSON.parse(localStorage.items);
                    } else {
                        return [];
                    }
                },
                componentWillUpdate: function componentWillUpdate(nextProps, nextState) {
                    localStorage.items = JSON.stringify(nextState.items);
                },
                render: function render() {
                    return React.createElement(
                        'div',
                        null,
                        this.showHeader(),
                        React.createElement(Form, {
                            onItemAdded: this.handleNewItem 
                        }),
                        React.createElement(
                            "div", {
                                id: "hotels"
                            },
                            this.state.items.map(this.buildItemNode)
                        )
                    );
                }
            });
            ReactDOM.render(React.createElement(HotelsStockholm, null), document.getElementById('hotelsDB'));
        </script>
    </body>
</html>