设置其值后无法单击复选框

时间:2019-09-09 04:08:30

标签: reactjs

设置值后,我无法选中/取消选中复选框。

我尝试同时使用onClick和onChange,但均无济于事。不知道还有什么尝试。我也将其绑定在构造函数中。

<section id="publish-section-5">
  <div class="Grid">
    <div class="Col Col--6">
      <div class="grid-block">
        <div class="Form-group publish-insights-input">
          <div class="Form-checkbox is-restricted">                        
              <input
              id="isRestricted"
              name="checkboxDefault"
              type="checkbox"
              checked={this.state.insightsDTO['isRestricted'] == 'Y'}
              onClick={this.handleCheckbox}
            />  
            <label for="restricted">Is Restricted</label>
          </div>
        </div>
      </div>
    </div>
  </div>
</section>        
handleCheckbox(e) {
  this.setState({
    insightsDTO: {
      ...this.state.insightsDTO, 
      [e.target.id]: e.target.checked
    }
  })
}  

即使设置了值,我也希望能够单击/取消单击它。

2 个答案:

答案 0 :(得分:1)

答案:

import React from 'react';

class Hello extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      insightsDTO: {
        checkboxDefault: true,
      },
    }
  }

  handleCheckbox = (e) => {
    this.setState({
      insightsDTO: {
        ...this.state.insightsDTO,
        [e.target.name]: !this.state.insightsDTO[e.target.name],
      },
    })
  }

  render() {
    return (
      <section id="publish-section-5">
        <div class="Grid">
          <div class="Col Col--6">
            <div class="grid-block">
              <div class="Form-group publish-insights-input">
                <div class="Form-checkbox is-restricted">                        
                    <input
                    id="isRestricted"
                    name="checkboxDefault"
                    type="checkbox"
                    checked={this.state.insightsDTO.checkboxDefault}
                    onChange={this.handleCheckbox}
                  />  
                  <label for="restricted">Is Restricted</label>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>
    )
  }
};

export default Hello;

答案 1 :(得分:0)

您要将'isRestricted'设置为true或false:

// isRestricted: true
[e.target.id]: e.target.checked

但是随后针对“ Y”进行测试:

// always false, because the value is never 'Y'
checked={this.state.insightsDTO['isRestricted'] == 'Y'}

尝试将其更改为:

checked={this.state.insightsDTO['isRestricted']}