2017-02-16 18 views
0

你好,我是新来的反应,我有一个关于复选框点击处理反应的问题。我想在选中复选框时显示div,如果取消选中复选框,请移除div。显示复选框中的组件点击反应

我这样做的方式只显示单击复选框时的div,但未选中时不会删除div。我如何在反应中做到这一点?

class QuestionOverlay extends Component { 

    constructor() { 

     super(); 

     this.showComments = this.showComments.bind(this); 

     this.state = { 

      showComponent: false, 
     }; 

    } 


    showComments = (e) => { 

     this.setState({ 

      showComponent: true, 

     }); 

    } 

    render() { 

      return (

       <div className="add_checkbox"> 

        <span>Enable Comments</span> 
        <input className="checkbox" type="checkbox" name="enable_comment" onClick={this.showComments} value="enable_comment"/> 

       </div> 



       {this.state.showComponent ? <div className="comments_preview_sample"></div> : null} 

     ) 
    } 
} 

回答

2

原因是你总是设定showComponent=true的价值,你需要在该复选框是选中重置状态变量,使用此:

showComments(e){ 

    this.setState({ 
     showComponent: e.target.checked, 
    }); 

} 

检查工作小提琴:https://jsfiddle.net/mrqutgbz/

一些事情你需要改变:

*你是returningrender 2个元素,一个div和另一个div从条件rendering。我们不能从render返回多个html元素,因此请将条件渲染放在主要的div中。

*您是bindingshowComments方法两次,一次在constructor和其他使用arrow,取出arrow,这不是必需的。

* Div是你rendering条件是空的,把一些内容。

+0

正是我所需要的感谢! – CraZyDroiD

+0

很高兴,帮助你:) –

1

您需要将onClick听众改为onChange。然后,重命名showCommentstoggleComments并实现它,像这样:

toggleComments(e) { 
    this.setState({ showComponent: e.target.checked }); 
} 
+0

谢谢,这是正确的! – CraZyDroiD

0

下面是你的代码的几个语法错误:在class规定不能使用=方式

  1. 功能。
  2. React渲染函数需要像div标签这样的根容器。

const { Component } = React; 
 
const { render } = ReactDOM; 
 

 
class QuestionOverlay extends Component { 
 
\t constructor(props) { 
 
\t \t super(props); 
 
\t \t this.state = { 
 
\t \t \t showComponent: false 
 
\t \t } 
 
\t \t this.showComments = this.showComments.bind(this); 
 
\t } 
 

 
\t showComments() { 
 
\t \t this.setState({ 
 
\t \t \t showComponent: !this.state.showComponent 
 
\t \t }); 
 
\t } 
 

 
\t render() { 
 
\t \t return (
 
\t \t \t <div> 
 
\t \t \t \t <div className="add_checkbox"> 
 
\t \t \t \t \t Enable Comments <br/> 
 
\t \t \t \t \t <input type="checkbox" onClick={this.showComments} /> 
 
\t \t \t \t </div> 
 
\t \t \t \t {this.state.showComponent ? <div className="comments_preview_sample">comments</div> : null} 
 
\t \t \t </div> 
 
\t \t); 
 
\t } 
 
} 
 

 
render(
 
\t <QuestionOverlay />, 
 
\t document.getElementById('root') 
 
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 
 
<div id="root"></div>

+0

它有一个根容器。我只是没有在这里包括它,因为它不是我的问题 – CraZyDroiD