链接到同一页面上的其他React组件

时间:2018-11-05 15:41:36

标签: reactjs react-router

我目前正在使用React创建一个网站。我的计划是要有一个导航栏,该导航栏的按钮可以链接到页面上的另一个组件,例如About部分。如何使用browserrouter做到这一点?

谢谢

1 个答案:

答案 0 :(得分:0)

这可能是最简单的方法:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.main = React.createRef();
  }
  renderMain() {
    return (
      <div style={styles.component}>
        <div style={styles.home}>
          <h1>Home</h1>
        </div>
        <div style={styles.about} ref={this.main}>
          <h1>About</h1>
        </div>
      </div>
    );
  }
  handleScroll = e => {
    e.preventDefault();
    const main = this.main.current;
    window.scrollTo({
      top: main.offsetTop,
      left: 0,
      behavior: "instant"
    });
  };
  render() {
    return (
      <div className="App">
        <BrowserRouter>
          <div>
            <div style={styles.nav}>
              <Link style={styles.link} to="/">
                Home{" "}
              </Link>
              <Link style={styles.link} onClick={this.handleScroll} to="/about">
                About{" "}
              </Link>
              <Link style={styles.link} to="/contact">
                Contact{" "}
              </Link>
            </div>

            <Switch>
              <Route exact path="/" component={() => this.renderMain()} />
              <Route exact path="/contact" render={() => <h1>Contact Us</h1>} />
              <Route render={() => <h1>Page not found</h1>} />
            </Switch>
          </div>
        </BrowserRouter>
      </div>
    );
  }
}

我在CodeSandbox上做了一个小型演示,向您展示了一个实时示例。

请在这里看看:https://codesandbox.io/s/ovlq4lpqp9

希望这会有所帮助。

编辑:您必须为要滚动到的组件分配一个“引用”,并且滚动事件必须通过nav链接中的onClick事件进行处理,如上面的代码所示。

我已经更新了我的codeandbox演示(请参阅上面的链接)以帮助您。

相关问题