react路由变化时页面置顶

只需要某一个页面置顶

  // 组件挂载
  componentDidMount() {
	window.scrollTo(0, 0);
  }

路由变化时页面置顶,可以写在路由组件界面或者顶层组件里,但是不能写在app.js里

// 路由相关配置 配置好了才能获取到 this.props.history 或者 this.props.location
import { withRouter } from "react-router";

class routers extends Component {
  // 第一种 路由变化时置顶
  componentDidMount() {
    this.props.history.listen(() => {
      //当路由切换时
      window.scrollTo(0, 0);
    });
  }
  // 第二种 props变化时置顶
  componentWillReceiveProps(nextProps) {
    //当路由切换时
    if (this.props.location !== nextProps.location) {
      window.scrollTo(0, 0);
    }
  }
  
  render() {
    return (
      <div>
          <Route exact path="/" component={Home} />
          <Route path="/products" component={Products} />
          ...
      </div>
    );
  }
}

export default withRouter(routers);


猜你喜欢

转载自blog.csdn.net/qq_36990322/article/details/89492093
今日推荐