Toasty 不会在挂钩列表后自动关闭或手动关闭

Toasty does not autoclose or manual close after hook list

我修改了代码,将 toast 堆栈动态生成到 ToastContainer 中作为通知系统。现在即使点击关闭按钮,toast 也不会自动关闭。

代码可以在https://react-bootstrap.github.io/components/toasts/

的dimiss区域内通过复制和过去复制
const Tsty = (props) => 
    <>
    <Toast show={ props.show } delay={ 3000 } autohide>
      <Toast.Header>
        <img src="holder.js/20x20?text=%20" className="rounded me-2" alt="" />
        <strong className="me-auto">{props.title}</strong>
        <small className="text-muted">{props.time}</small>
      </Toast.Header>
      <Toast.Body>{props.body}</Toast.Body>
    </Toast>
    </>
render(<Tsty />);

function Example() {
  const [listNtfy, setNtfy] = useState([]);
  const style = { position: 'fixed', bottom: '60px', right: '10px', zIndex: '1000'}
  return (
    <>
    <Button onClick={() => {setNtfy([...listNtfy, {title: 'title #', time: 'now', body:  new Date().toString(), show : true }])}}>Add Ntfy</Button>
    <ToastContainer style={style}>
      { listNtfy.map( (x,i) => <Tsty show={ x.show } title={x.title + i} time={x.time} body={x.body} key={i} /> ) }
    </ToastContainer>
    </>
  );
}

render(<Example />);

哪里出错了?

这不会关闭导致 Tosty 挂钩显示 属性 不存在于挂钩中。要解决它,您可以定义 show 属性 并创建一个函数来隐藏它。当所有的ntfys都关闭后,列表就被清理了。

const Tsty = (props) => 
    <>
    <Toast show={ props.show } onClose={ () => {props.fcn(props.idx) } } delay={ 5000 } autohide>
      <Toast.Header>
        <img src="holder.js/20x20?text=Q" className="rounded me-2" alt="" />
        <strong className="me-auto">{props.title}</strong>
        <small className="text-muted">{props.time}</small>
      </Toast.Header>
      <Toast.Body>{props.body}</Toast.Body>
    </Toast>
    </>
render(<Tsty />);

function Example() {
  const [listNtfy, setNtfy] = useState([]);
  // Function to autohide the ntfys
  const autoHide = (key) => { 
    // Set visibility of Ntfy to hidden
    listNtfy.filter((x,i) => i === key)[0].show = false;
    // Apply the change
    setNtfy([...listNtfy]);
    // Check all notifications is hide (if yes, reset the list)
    if (listNtfy.every(v => v.show === false))
      setNtfy([]);
    };
  const style = { position: 'fixed', bottom: '60px', right: '10px', zIndex: '1000'}
  return (
    <>
    <Button onClick={() => {setNtfy([...listNtfy, { title: 'title #' + listNtfy.length, time: 'now', body:  new Date().toString(), show : true }])}}>Add Ntfy</Button>
    <ToastContainer style={style}>
      { listNtfy.map( (x,i) => <Tsty show={ x.show } title={x.title} time={x.time} body={ x.body } key={i} idx={i} fcn={ autoHide } /> )}
    </ToastContainer>
    </>
  );
}

render(<Example />);