React实现移动端导航栏返回事件逻辑

  一直纠结导航栏返回之后用户如果按了手机上的物理返回键怎么处理,原来用history就好了啊!

header.jsx中:

import React from 'react';
import PropTypes from 'prop-types';
import './Header.css';

export default function Header(props) {
    const {
        onBack,
        title,
    } = props;

    return (
        <div className="header">
            <div className="header-back" onClick={onBack}>
                <svg width="42" height="42">
                    <polyline
                        points="25,13 16,21 25,29"
                        stroke="#fff"
                        strokeWidth="2"
                        fill="none"
                    />
                </svg>
            </div>
            <h1 className="header-title">
                { title }
            </h1>
        </div>
    );
}

Header.propTypes = {
    onBack: PropTypes.func.isRequired,
    title: PropTypes.string.isRequired,
};

在app.jsx中:

    const onBack = useCallback(() => {
        window.history.back();
    }, []);

这里加入一个空数组对象是避免header一直重复重渲染。

发布了80 篇原创文章 · 获赞 82 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_42893625/article/details/104291241