2017-08-07 91 views
1

我真的很难明白这段代码中发生了什么。我试图在ReactJS中有一个复选框。该框不检查/取消选中onClick,但它确实将选择保存为true/false。ReactJS中的复选框问题

帮助将非常感激,我可以阐述如有必要。

截图 - 复选框从未被选中,甚至当你点击它的价值已经从假变为真

enter image description here

export default class checkboxEdit extends Component { //sample change 
 
    constructor(props){ 
 
     super(props); 
 
     this.onChangeHandler = this.onChangeHandler.bind(this); 
 
     this.onBlur = this.onBlur.bind(this); 
 
    } 
 
    onChangeHandler(event){ 
 
     event.preventDefault() 
 
     this.props.onChange({ 
 
      target:{ 
 
       value: event.target.checked 
 
      } 
 
     }); 
 
     if (this.props.onClick && Object.prototype.toString.call(this.props.onClick) == '[object Function]') { 
 
      try { 
 
       this.props.onClick(event); 
 
      } catch (err) { 
 
       console.log('Suppressing error', err); 
 
      } 
 
     } 
 
    } 
 
    
 
    onBlur(event) { 
 
\t \t if (this.props.onBlur && Object.prototype.toString.call(this.props.onBlur) == '[object Function]') { 
 
        this.props.onBlur(event); 
 
     } 
 
\t \t 
 
\t \t if (this.props.onBlurChange && Object.prototype.toString.call(this.props.onBlurChange) == '[object Function]') { 
 
        this.props.onBlurChange (event); 
 
       } 
 
\t } 
 
    
 
    render() { 
 
     return (
 
      <p className='form-control-static'> 
 
       <span className='checkbox'> 
 
        <label style={{minWidth:'50px'}} className='checkbox'> 
 
         <input style={{minWidth:'50px'}} type='checkbox' 
 
         onMouseEnter={this.props.onMouseOver} 
 
         onMouseLeave={this.props.onMouseOut} 
 
         onChange={this.onChangeHandler} 
 
         onBlur={this.onBlur} 
 
         onFocus={this.props.onFocus} 
 
         aria-required={(this.props.required) ? true : false} 
 
         value="on" 
 
         checked={(this.props.value) ? "checked" : ""} 
 
         className='form-check-input' 
 
         /> 
 
         <span>{this.props.checkboxText}</span> 
 
        </label> 
 
        <small className='form-text text-muted'>{this.props.descriptiveText}</small> 
 
       </span> 
 
      </p> 
 
     ); 
 
    } 
 
}

回答

0

由于显示的文档中, checked属性应该是布尔值而不是字符串。所以,你可以尝试:

checked={this.props.value} 

而且我不知道该value属性的存在是否是导致您的问题或没有。你可以尝试删除它。

编辑

在调用您的处理程序event.preventDefault显然打破了正常工作的反应更新。有关工作解决方案,请参阅https://stackblitz.com/edit/react-t2he58?embed=1&file=CheckBoxEdit.js

+0

我编辑了我的答案后发布它与此编辑。它现在工作吗? –

+0

我用您的建议替换了上一个选中的行。 我也尝试删除值属性,但这并没有影响任何方式。 现在在第一次点击复选框时,'True'的值被保存。第二次点击会使该框显示为选中状态。 我以为我有这两个在同一时间发生,但它似乎以某种方式分开 - 你有任何进一步的建议?谢谢! – Salki

+0

请参阅我的编辑。它现在可以与你的例子 –