gpt4 book ai didi

javascript - 在 React 16 中实现隐藏/显示

转载 作者:行者123 更新时间:2023-11-30 14:04:39 24 4
gpt4 key购买 nike

我正在尝试在 react 16 中实现隐藏/显示按钮如果我点击一个按钮,那么它应该显示 Card按钮,如果我点击 card它应该隐藏的按钮 card按钮,我已经实现了这个但是我使用了componentwillReceiveprops在 React 16 中不推荐的 Prop 我试过了 static getDerivedStateFromProps但是当我这样做时它会被调用 setStatehandleclick working js fiddle

如何在不使用 componentwillReceiveprops 的情况下获得相同的结果?

下面是我的代码

class Test extends React.Component {

state ={
show: false
}

show(){
this.setState({show: true})
}



render() {
return (
<div className="App">
<button onClick={this.show.bind(this)}>show the button</button>
{this.state.show && <Notification show={true}/>}
</div>
)
}
}



const style = {
marginBottom: '0.5rem',
float: 'right',
boxShadow: '0 4px 8px 0 rgba(0, 0, 0, 0.1)',
marginTop: '-9px'
};



class Notification extends React.Component {

constructor(props){
super(props);
this.state ={
open: true
}
}

componentWillReceiveProps(props){
console.log('will recieve props')
this.setState({open: props.show})
}


handleClick(){
this.setState({open: false})
}

render(){
if(!this.state.open){
return null
}

return (
<div className="test">
<div>
<button onClick={()=>this.handleClick()}>Card</button>
</div>
</div>
)
}

};




ReactDOM.render(
<Test name="World" />,
document.getElementById('container')
);

最佳答案

与其复杂,不如简单,在父组件上使用toggleShow,如果show为true,只挂载Notification,传入toggleShow 来自父级的 Prop ,以便能够从我们的子组件中切换它

class Test extends React.Component {
constructor() {
super();
this.state = { show: false };
this.toggleShow = this.toggleShow.bind(this);
}

toggleShow() {
this.setState(prevState => ({ show: !prevState.show }));
}

render() {
return (
<div className="App">
<button onClick={this.toggleShow}>show the button</button>
{this.state.show && <Notification hideNotification={this.toggleShow} />}
</div>
);
}
}

const Notification = ({ hideNotification }) => (
<div className="test">
<div>
<button onClick={hideNotification}>Card</button>
</div>
</div>
);

关于javascript - 在 React 16 中实现隐藏/显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55673590/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com