2017-02-16 17 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