当用户在功能性 React 组件中使用触摸屏时,用按钮隐藏 div

Hide div with buttons when user uses a touch screen in a functional react component

我想在用户使用触摸屏时隐藏 div。这是一个反应js功能组件。

我要隐藏的div看起来是这样的:

    <div className="scrollButtons">
                    <button
                        className={count <= 0 ? 'buttonLeftOpacity' : 'buttonLeft'}
                        type="button"
                        onMouseDown={() => clickHandlerLeft()}
                    >
                        {'<'}
                    </button>
                    <button className="buttonRight" type="button" onMouseDown={() => clickHandlerRight()}>
                        {'>'}
                    </button>
                </div>
            </>

我用来检测用户是否在触摸屏上的代码是这样的:

    window.addEventListener('touchstart', function userTouch() {
        console.log(userTouch());
    });

当用户使用触摸屏时,我如何使用该代码隐藏 div? 提前致谢!

制作一个不会显示的class

.example {
display:none; 
}

然后添加这个

 window.addEventListener('touchstart', function userTouch() {
  var element = document.getElementById("scrollbuttons"); // selecting the element you want to edit, make sure to add the ID to the button if you are using this method. 
  element.classList.add("example"); //add invisible className
});

所以,我就是这样解决的。通过使用 React 中的“useState”,我将 show 默认设置为 true,如果用户在触摸屏上,则设置为 false。然后,我使用该状态显示或隐藏 touchbuttons-div 值是否为真。

const [show, setShow] = useState(true);

    window.addEventListener('touchstart', function userTouch() {
        setShow(false);
    })

{show ? (
                <>
                    <div className="scrollButtons" id="scrollButtons">
                        <button
                            className={count <= 0 ? 'buttonLeftOpacity' : 'buttonLeft'}
                            type="button"
                            onMouseDown={() => clickHandlerLeft()}
                        >
                            {'<'}
                        </button>
                        <button className="buttonRight" type="button" onMouseDown={() => clickHandlerRight()}>
                            {'>'}
                        </button>
                    </div>
                </>
            ) : (
                <></>
            )}