React 功能组件 - 如何从内部删除组件?
React Functional Components - how to delete component from within?
我有一个基于用户操作显示的警报组件:
export default function Alert({text, type, hideable = true, stick = true}) {
const [hide, setHide] = useState(false);
const [id, setId] = useState(makeId(5));
const alertEl = (
<div key={id} id={id} className={"fade alert alert-" + type} role="alert">
{hideable
? <span className="icon-close close" onClick={e => fadeOut()}> </span>
: ''
}
{text}
</div>
);
function fadeOut() {
document.getElementById(id).classList.add('fade-out');
window.setTimeout(() => {
setHide(true);
}, 500)
}
useEffect(() => {
if (!stick) {
window.setTimeout(() => fadeOut(), 3000);
}
}, [])
if (hide) return '';
return alertEl;
}
是这样使用的:
setResponseAlert(<Alert
text="Please check the field errors and try again."
type="danger" stick={false} hideable={false}
/>)
问题是实例化 Alert 组件仍然返回旧组件。 Alert组件消失后如何实现移除?
传递 setResponseAlert
以便可以使用 null
或 undefined
调用它,而不是使用 hide
状态。
此外,不要使用 getElementById
,因为这是 React,您应该以某种方式将淡入淡出 class 置于状态:
export default function Alert({text, type, setResponseAlert, hideable = true, stick = true}) {
const [className, setClassName] = useState("fade alert alert-" + type);
function fadeOut() {
setClassName(className + ' fade-out');
window.setTimeout(() => {
setResponseAlert(null);
}, 500)
}
useEffect(() => {
if (!stick) {
window.setTimeout(fadeOut, 3000);
}
}, [])
return (
<div role="alert" className={className}>
{hideable
? <span className="icon-close close" onClick={e => fadeOut()}> </span>
: ''
}
{text}
</div>
);
}
我有一个基于用户操作显示的警报组件:
export default function Alert({text, type, hideable = true, stick = true}) {
const [hide, setHide] = useState(false);
const [id, setId] = useState(makeId(5));
const alertEl = (
<div key={id} id={id} className={"fade alert alert-" + type} role="alert">
{hideable
? <span className="icon-close close" onClick={e => fadeOut()}> </span>
: ''
}
{text}
</div>
);
function fadeOut() {
document.getElementById(id).classList.add('fade-out');
window.setTimeout(() => {
setHide(true);
}, 500)
}
useEffect(() => {
if (!stick) {
window.setTimeout(() => fadeOut(), 3000);
}
}, [])
if (hide) return '';
return alertEl;
}
是这样使用的:
setResponseAlert(<Alert
text="Please check the field errors and try again."
type="danger" stick={false} hideable={false}
/>)
问题是实例化 Alert 组件仍然返回旧组件。 Alert组件消失后如何实现移除?
传递 setResponseAlert
以便可以使用 null
或 undefined
调用它,而不是使用 hide
状态。
此外,不要使用 getElementById
,因为这是 React,您应该以某种方式将淡入淡出 class 置于状态:
export default function Alert({text, type, setResponseAlert, hideable = true, stick = true}) {
const [className, setClassName] = useState("fade alert alert-" + type);
function fadeOut() {
setClassName(className + ' fade-out');
window.setTimeout(() => {
setResponseAlert(null);
}, 500)
}
useEffect(() => {
if (!stick) {
window.setTimeout(fadeOut, 3000);
}
}, [])
return (
<div role="alert" className={className}>
{hideable
? <span className="icon-close close" onClick={e => fadeOut()}> </span>
: ''
}
{text}
</div>
);
}