简体   繁体   English

Reactjs route `onEnter` 方法未调用,scrolltoview 不起作用

[英]Reactjs route `onEnter` method not calling, scrolltoview not works

according to my requirement, when a user click on根据我的要求,当用户点击

<Link to="/products/shoe#product9">Go to projects and focus id 9</Link> i would like to show him the product.( hello page ) for that i do this: <Link to="/products/shoe#product9">Go to projects and focus id 9</Link>我想向他展示产品。(你好页面)为此我这样做:

import React from "react";从“反应”导入反应; import { Link, Route, Switch, Redirect } from "react-router-dom";从“react-router-dom”导入{链接、路由、切换、重定向};

import "./products.scss";

const Shoes = React.lazy(() => import("./shoes/shoes.component"));
const Cloths = React.lazy(() => import("./cloths/cloths.component"));

function hashScroll() {
  alert("called");
  const { hash } = window.location;
  if (hash !== "") {
    setTimeout(() => {
      const id = hash.replace("#", "");
      const element = document.getElementById(id);
      if (element) element.scrollIntoView();
    }, 0);
  }
}

export default class Products extends React.Component {
  render() {
    return (
      <div>
        <header>
          <Link to="/products/shoe">Shoes</Link>
          <Link to="/products/cloths">Cloths</Link>
        </header>
        <h1>Products page</h1>
        <main>
          <Switch>
            <Redirect exact from="/products" to="/products/shoe" />
            <Route path="/products/shoe" onEnter={hashScroll}>
              <Shoes />
            </Route>
            <Route path="/products/cloths">
              <Cloths />
            </Route>
          </Switch>
        </main>
      </div>
    );
  }
}

I attached a onEnter function to call and scroll.我附加了一个onEnter function 来调用和滚动。 so when there is a #hash let it scroll.所以当有#hash时让它滚动。 but it's not works at all.但它根本不起作用。 any one help me?有人帮我吗? please navigate to Hello page, from you click the link to go to products page.请导航到Hello页面,从您点击链接到 go 到产品页面。

Live Demo 现场演示

onEnter is no longer working in react-router onEnter不再在 react-router 中工作

What you can do is pass a prop to the component您可以做的是将道具传递给组件

<Shoes onEnter={hashScroll} />

inside the Shoes component execute it on componentDidMount .Shoes组件内部,在componentDidMount上执行它。

componentDidMount = () => {
    if (this.props.onEnter) {
        this.props.onEnter();
    }        
};

demo演示

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

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