您需要定义一个函数来隐藏
Alert
在父组件本身中,并将其传递给子组件。
const hideAlert = () => {
setAlert(prevState => ({
...prevState,
show: !prevState.show
}))
}
然后你可以把这个传给
警觉的
组件,
<Alert show={alert.show} style={alert.style} message={alert.message} hideAlert={hideAlert}/>
在警报组件中,无需再次将道具存储到该状态。你应该直接用道具,
const Alert = ({show, style, message, hideAlert}) => {
return (
<>
{ show ? <div className="col"> //directly use props here to show alert
<div className={"alert shadow alert-"+style} role="alert">
{message}
<button type="button" className="close" aria-label="Close" onClick={hideAlert}>
<span aria-hidden="true">×</span>
</button>
</div>
</div>
:
<></>
}
</>
);
}
Demo