2016-05-01 100 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(...):只能更新挂载或挂载组件 - –