2016-05-01 103 views
10

我有一個部件:如何在點擊React-redux時顯示/隱藏組件?

class CommentBox extends Component { 
    render() { 
     return (
      <div> 
       <p>Some comment</p> 
       <a>Post a reply to this comment</a> 
      </div> 
      <ReplyForm /> 
     ) 
    } 
} 

我需要這個ReplyForm初始加載到被隱藏。如何通過點擊標籤觸發它的狀態?

+0

實際上您是否在任何地方使用Redux? –

+0

幾個相關的帖子[這裏](https://stackoverflow.com/q/24502898/465053)和[這裏](https://stackoverflow.com/q/29913387/465053)。 – RBT

回答

19

您應該添加一些標誌到CommentBox的狀態。如果此標誌的值爲false,則不顯示ReaplyFrom,反之亦然。下面是代碼和工作示例http://codepen.io/anon/pen/KzrzQZ

class ReplyForm extends React.Component { 
    constructor() { 
    super() 
    } 
    render(){ 
    return(
     <div>I'm ReplyForm</div> 
    ) 
    } 
} 

class CommentBox extends React.Component { 
    constructor() { 
    super(); 
    this.state = { 
     showReply: false 
    } 
    } 
    onClick(e){ 
    e.preventDefault(); 
    this.setState({showReply: !this.state.showReply}) 
    } 
    render() { 
    return (
     <div> 
     <p>Some comment</p> 
     <a onClick={this.onClick.bind(this)} href='#'>Post a reply to this comment</a> 
     {this.state.showReply && < ReplyForm/>} 
     </div> 
    ) 
    } 
} 
+1

您正在組件中改變狀態。定義狀態是由全球商店維護和變異 –

+0

@AtabtabNaveed我只是試圖表明你不需要Redux或任何其他額外的庫來執行這樣的操作,但我想你是對的,如果你使用Redux然後'showReply '應該放在店裏 – t1m0n

+0

這個視頻清楚地說明了https://youtu.be/Mo2_UPkZjJU – Prem

3

這個怎麼樣?

class CommentBox extends Component { 
    constructor() { 
    super(); 
    this.state = { 
     showForm: false 
    } 
    } 

    render() { 
    const showHide = { 
     'display': this.state.showStatus ? 'block' : 'none' 
    }; 

    const showReplyForm =() => { 
     this.setState({showForm: true}); 
    }; 

    return (
     <div> 
     <div> 
      <p>Some comment</p> 
      <a onClick={showReplyForm}>Post a reply to this comment</a> 
     </div> 
     <div style={showStatus}> 
      <ReplyForm /> 
     </div> 
     </div> 
    ) 
    } 
} 
+0

這種方式正在阻止我得到如下消息 - 警告:setState(...):只能更新掛載或掛載組件 - –