我试图隐藏StickyFooterDynamic onCLick。我设法用css隐藏了它,但是我想使用React的状态将它从DOM onClick中完全删除。有人有关于如何做到这一点的建议吗? ES6方式。
class StickyFooterDynamic extends React.Component {
constructor(props) {
super(props);
this.state = {
visible: true,
}
}
onClick() {
this.setState(prevState => ({
visible: !prevState.visible,
}))
}
render() {
if (!this.state.visible) {
return null
}
const { url, service } = this.props;
return (
<StickyFooter>
<div className='sticky-footer-dynamic-wrapper'>
<div className='main-content'>
<div className='copy-wrapper'>
<img className='sticky-footer-dynamic-img' alt='Repair Icon' src={iconRepair} />
<h3 className='sticky-footer-copy'>Want a free quote for {service}?</h3>
</div>
<a className='sticky-footer-dynamic-btn btn' href={url}>GET<i className="right-arrow"></i></a>
<a href='#' className='sticky-footer-close' onClick={this.onClick}></a>
</div>
</div>
</StickyFooter>
);
}
}
export default StickyFooterDynamic;
答案 0 :(得分:1)
您可以切换内部状态并返回null
:
class StickyFooterDynamic extends React.Component {
constructor(props) {
super(props)
this.state = {
visible: true,
}
this.onClick = this.onClick.bind(this)
}
onClick(event) {
event.preventDefault()
this.setState(prevState => ({
visible: !prevState.visible,
}))
}
render() {
if (!this.state.visible) {
return null
}
const { url, service } = this.props
return (
<StickyFooter>
...
<a href="#" className='sticky-footer-close' onClick={this.onClick}></a>
</StickyFooter>
)
}
}