我有一个组件:
class CommentBox extends Component {
render() {
return (
<div>
<p>Some comment</p>
<a>Post a reply to this comment</a>
</div>
<ReplyForm />
)
}
}
我需要在初始加载时隐藏此ReplyForm。如何通过点击标签触发它的状态?
答案 0 :(得分:20)
您应该为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 :(得分:4)
这个怎么样?
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>
)
}
}
答案 2 :(得分:0)
您可以尝试rc-if-else模块
npm install --save rc-if-else
import React from 'react';
import { If } from 'rc-if-else';
class CommentBox extends Component {
constructor() {
super();
this.state = {
showForm: false
}
}
render() {
const showReplyForm = () => {
this.setState({showForm: true});
};
return (
<div>
<div>
<p>Some comment</p>
<a onClick={showReplyForm}>Post a reply to this comment</a>
</div>
<If condition={this.state.showStatus}>
<ReplyForm />
</If>
</div>
)
}
}