繁体   English   中英

如何使用Javascript在点击时删除HTML div

[英]How to remove HTML div on click using Javascript

所以我有这个Display()函数,它从谷歌日历中获取事件,该函数返回要在屏幕上呈现的元素列表(每个元素都与一个滑块相关联)(请参阅Display()函数的返回语句)并呈现他们在这里看到。 因此,每个元件带有一个Remove按钮,这样我可以使用从页面中移除不想要的元素hideMe()内部函数Display()函数。 hideMe()函数似乎做的工作,但是,它删除了相关网页上的所有元素所看到这里 所以我正在努力弄清楚我应该修复什么,以便当我单击“ Remove按钮时,它只会删除与该remove按钮关联的元素和滑块。 我是 React 和 JavaScript 的新手,所以请帮忙。 任何帮助表示赞赏,并提前感谢您。

function Display() {
    const isMounted = useRef(true);
    const [items, saveItems] = useState([]);
    const [visible, setVisible] = useState(true);
    const [fading, setFading] = useState(false);

    useEffect(() => {
        return () => {
            isMounted.current = false;
        };
    }, []);

    useEffect(() => {
        (async () => {
            const items = await fetchItems();
            //Do not update state if component is unmounted
            if (isMounted.current) {
                saveItems(items);
            }
        })();
    }, []);

    function hideMe() {
        setFading(true);
        setTimeout(() => setVisible(false), 650);
    }

    return (
        <Tab.Pane attached={false}>
            <h5>Rate stress level for each event</h5>
            <br/>
            {items.map(item => (
                    <div key={item.id} isvisible={!fading}
                         style={visible ? null : { display: "none" }}>
                        <Typography id="discrete-slider-restrict" gutterBottom>
                           {item}
                           <button onClick={hideMe}>Remove</button>
                        </Typography>
                        <PrettoSlider aria-label="pretto slider" defaultValue={98} step={null}marks={stresslevel}/>
                    </div>
            ))}
        </Tab.Pane>
    )
}

在我看来,这个问题正在发生是因为所有元素都处于相同的状态,或者我会说它们都共享相同的状态。 所以,这对所有人都执行。 如果您可以将其提取到新组件并在那里使用 hideMe 功能。 我确信这将适用于每个单独的元素。

这是我的建议,请通过以下。 可能你需要稍微调整一下。

您可以在单独的组件中提取元素,例如:

const Item = props => {

     const [visible, setVisible] = useState(true);
     const [fading, setFading]   = useState(false);

     function hideMe() {
         setFading(true);
         setTimeout(() => setVisible(false), 650);
     }

     return (
         <div isvisible={!fading} style={visible ? null : { display: "none" }}>
            <Typography id="discrete-slider-restrict" gutterBottom>
                  {item}
               <button onClick={hideMe}>Remove</button>
            </Typography>
            <PrettoSlider aria-label="pretto slider" defaultValue={98} 
                          step={null} marks={stresslevel}/>
         </div>
     );

};
export default Item;

然后你可以像这样使用它:

  // import Item
{items.map(item => (
    <Item key={item.id} itemObj={item} /> 
    // in case if you need item obj then props.itemObj will get you the object.
))}

通过这种方式,您可以使用单独的特定 Item 组件来管理hideMe功能。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM