使用引导程序和单选按钮做出反应

时间:2020-06-24 09:07:35

标签: javascript reactjs react-bootstrap

我正在尝试在React(我一直使用)中使用单选按钮,但是这次使用react-bootstrap。 我有两个单选按钮,我只想检查其中一个并获得该值。

import React, { useState } from "react";
import { Form, Button } from "react-bootstrap";

const StandAdd = () => {
  const [item, setItem] = useState({
    kindOfStand: ""
  });

  const { kindOfStand } = item;

  const handleInputChange = event => {
    event.preventDefault();
    setItem({ ...item, [event.target.name]: event.target.value });
  };

  const handleSubmit = event => {
    event.preventDefault();
    alert(`${kindOfStand}`);
  };

  return (
    <form onSubmit={handleSubmit}>
      <Form.Group controlId="kindOfStand">
        <Form.Check
          type="radio"
          aria-label="radio 1"
          label="Design"
          onChange={handleInputChange}
          checked={kindOfStand === "design"}
          // value="design" // <-- once enabled I can't select it
        />
        <Form.Check
          type="radio"
          aria-label="radio 2"
          label="Food"
          onChange={handleInputChange}
          checked={kindOfStand === "food"}
          // value="food" // <-- once enabled I can't select it
        />
      </Form.Group>
      <Button variant="primary" type="submit">
        Submit
      </Button>
    </form>
  );
};

export default StandAdd;

Codesandbox链接:https://codesandbox.io/s/react-bootstrap-radio-button-1d443

关于如何获得价值的任何想法?

1 个答案:

答案 0 :(得分:1)

value提供一个Form.Check属性,然后在您单击无线电btn时使用e.target.value获取该值。使用e.persist();避免出现以下错误:

出于性能原因,此合成事件被重用。如果你是 看到这一点,您正在访问方法currentTarget 已发布/无效的合成事件

const StandAdd = () => {
  const [item, setItem] = useState({ kindOfStand: "", another: "another" });

  const { kindOfStand } = item;

  const handleChange = e => {
    e.persist();
    console.log(e.target.value);

    setItem(prevState => ({
      ...prevState,
      kindOfStand: e.target.value
    }));
  };

  const handleSubmit = e => {
    e.preventDefault();
    alert(`${kindOfStand}`);
  };

  return (
    <form onSubmit={handleSubmit}>
      <Form.Group controlId="kindOfStand">
        <Form.Check
          value="design"
          type="radio"
          aria-label="radio 1"
          label="Design"
          onChange={handleChange}
          checked={kindOfStand === "design"}
        />
        <Form.Check
          value="food"
          type="radio"
          aria-label="radio 2"
          label="Food"
          onChange={handleChange}
          checked={kindOfStand === "food"}
        />
      </Form.Group>
      <Button variant="primary" type="submit">
        Submit
      </Button>
    </form>
  );
};

Demo

相关问题