Reactjs 如何在React redux中单击时显示/隐藏组件?

Reactjs 如何在React redux中单击时显示/隐藏组件?,reactjs,redux,Reactjs,Redux,我有一个组成部分: class CommentBox extends Component { render() { return ( <div> <p>Some comment</p> <a>Post a reply to this comment</a> </div>

我有一个组成部分:

class CommentBox extends Component {
    render() {
        return (
            <div>
                <p>Some comment</p>
                <a>Post a reply to this comment</a>
            </div>
            <ReplyForm />
        )
    }
}
类CommentBox扩展组件{
render(){
返回(
一些评论

发布对此评论的回复 ) } }
我需要在初始加载时隐藏此
ReplyForm
。如何通过点击标签来触发它的状态?

这个怎么样

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>
    )
  }
}
类CommentBox扩展组件{
构造函数(){
超级();
此.state={
展示形式:假
}
}
render(){
常量showHide={
“显示”:this.state.showStatus?“块”:“无”
};
常量showReplyForm=()=>{
this.setState({showForm:true});
};
返回(
一些评论

发布对此评论的回复 ) } }
您应该在
评论框的状态中添加一些标志。如果此标志的值为
false
,则不显示
ReaplyFrom
,反之亦然。下面是代码和工作示例

class ReplyForm扩展了React.Component{
构造函数(){
超级()
}
render(){
返回(
我正在回复
)
}
}
类CommentBox扩展了React.Component{
构造函数(){
超级();
此.state={
回答:错
}
}
onClick(e){
e、 预防默认值();
this.setState({showReply:!this.state.showReply})
}
render(){
返回(
一些评论

{this.state.showReply&& ) } }
您可以尝试使用该模块

npm安装--如果没有,请保存rc
从“React”导入React;
从'rc If else'导入{If};
类CommentBox扩展组件{
构造函数(){
超级();
此.state={
展示形式:假
}
}
render(){
常量showReplyForm=()=>{
this.setState({showForm:true});
};
返回(
一些评论

发布对此评论的回复 ) } }
您是否真的在任何地方使用Redux?很少有相关帖子和内容。您正在改变组件内部的状态。这在Redux中可以吗?根据它的定义,状态是由一个全局存储维护和变异的。@aftAbnaved我只是试图表明您不需要Redux或任何其他额外的库来执行这样的操作。但是我想你是对的,如果你使用的是Redux,那么应该将
showReply
放在商店里。使用这个模型,如果我在试图显示或隐藏的某个组件中使用setState,我会收到类似“警告:setState(…):只能更新已安装或正在安装的组件”的消息。无论如何都有办法避免这个问题吗?使用
setState()
不是违背了使用Redux/不回答问题的目的吗?OP要求提供一个Redux解决方案,所以我想他们希望按照这种方式管理状态。这种方式会阻止我收到诸如--Warning:setState(…):只能更新已安装或正在安装的组件”之类的消息--
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>
    )
  }
}