簡體   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