【问题标题】:How to make my checkbox to be clicked only once and other are unchecked in React.js如何使我的复选框仅被单击一次,而其他在 React.js 中未选中
【发布时间】:2020-07-12 16:55:44
【问题描述】:

我按照教程创建了一个表单,其中包含要单击的多个复选框。但是,在另一种情况下,我只需要检查一个框。复选框的值是动态的,您永远不知道会创建多少个复选框。但是,只能点击一个。你能帮我找到解决办法吗谢谢。

import React, { Component } from 'react';
import Checkbox from "./Checkbox.component";

class PatientSelectTiming extends Component {
state = { 
      options: [...this.props.props],
      checkboxes: [...this.props.props].reduce(
        (options, option) => ({
          ...options,
          [option]: false
        }),
        {}
      ),
      appointmentSlots: null
  };

  handleCheckboxChange = e => {
    const { name } = e.target;
    

    this.setState(prevState => ({
      checkboxes: {
        ...prevState.checkboxes,
        [name]: !prevState.checkboxes[name]
      }
    }))
    }

  handleFormSubmit = formSubmitEvent => {
    formSubmitEvent.preventDefault();
    Object.keys(this.state.checkboxes)
      .filter(checkbox => this.state.checkboxes[checkbox])
      .forEach(checkbox => { 
        let appointmentSlot = [];  
        appointmentSlot.push(checkbox); 
        console.log(appointmentSlot);
        this.setState({appointmentSlots: appointmentSlot})
        localStorage.setItem('appointmentSlots', JSON.stringify(appointmentSlot))     
    });  
  };

  createCheckbox = option => (
    <Checkbox
      label={option}
      isSelected={this.state.checkboxes[option]}
      onCheckboxChange={this.handleCheckboxChange}
      key={option}
    />
  );

  createCheckboxes = () => this.state.options.map(this.createCheckbox);

  render() {
    return (
      <div>
        <p>Only select one item and only first date clicked will be your time</p>
            <form onSubmit={this.handleFormSubmit}>
              {this.createCheckboxes()}
                <button type="submit">
                  Save
                </button>
            </form>
    {this.state.appointmentSlots === null ? <p>Click on any slot to get your time.</p> : <p>Your time is {JSON.parse(localStorage.getItem("appointmentSlots"))}</p>}
    </div>
          )
    }
  }
export default PatientSelectTiming;

【问题讨论】:

  • 使用同名的单选按钮,只能选中一个。

标签: javascript reactjs react-props react-component react-state


【解决方案1】:

您可以使用单选按钮 https://www.w3schools.com/tags/att_input_type_radio.asp 单选按钮与复选框相同,但只允许用户选中 1 个选项。

【讨论】:

    猜你喜欢
    • 2018-10-21
    • 2021-08-09
    • 1970-01-01
    • 1970-01-01
    • 2011-05-24
    • 2023-04-05
    • 1970-01-01
    相关资源
    最近更新 更多