如何在点击React-redux时显示/隐藏组件?
问题描述:
我有一个部件:如何在点击React-redux时显示/隐藏组件?
class CommentBox extends Component {
render() {
return (
<div>
<p>Some comment</p>
<a>Post a reply to this comment</a>
</div>
<ReplyForm />
)
}
}
我需要这个ReplyForm初始加载到被隐藏。如何通过点击标签触发它的状态?
答
您应该添加一些标志到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>
)
}
}
答
这个怎么样?
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(...):只能更新挂载或挂载组件 - –
实际上您是否在任何地方使用Redux? –
几个相关的帖子[这里](https://stackoverflow.com/q/24502898/465053)和[这里](https://stackoverflow.com/q/29913387/465053)。 – RBT