使用react路由器导航到元素id

时间:2018-01-13 01:56:56

标签: reactjs routes react-router

我正在尝试使用react路由器导航到网页上的特定元素。 我尝试过BrowserRouter实现,但似乎可以让它们工作。

我认为可能通过Id引用元素是不可行的,因为在元素实际呈现给DOM之前对元素的调用发生了。但是,即使在页面完全加载后,链接仍然无法正常工作。

路由器

const history = createHistory();

class AppRouter extends React.Component {
  render() {
    return (
      <BrowserRouter
        history={history}>
        <div>
          <Menu/>
          <Switch>
            <Route path="/" component={HomePage} exact={true} />
            <AdminRoute path="/admin" component={AdminPage} />
            <Route path="/plays" component={PlaysPage} />
            <Route path="/prose" component={ProsePage} />
            <Route path="/events" component={EventsPage} />
            <Route path="/content/:id" component={ContentDisplay} />
            <Route path="/create-account" component={CreateAccountPage} />
            <Route component={NotFoundPage} />
          </Switch>
          <Footer />
        </div>
      </BrowserRouter>
    );
  }
}

export default AppRouter;

export { history };

链接

<Link to="/plays#ten-minute-plays" className="menu__nav menu__nav--hitbox">
    10 Minute Plays
</Link>

元素

class PlaysPage extends React.Component{
  state = {
    plays: this.props.content
  };

  componentDidMount(){
    this.props.startSetContent()
      .then(() => {
        this.setState({ plays: this.props.content });
        history.push(`/${window.location.pathname}`)
      });
  }

  render () {
    return(
      <div className="plays"> 
        <div className="ten-min-plays">
          <h1 id="ten-minute-plays" className="ten-min-plays__title">
            10 Minute Plays
          </h1>
        <div/>
      <div/>
    )
  }
}

0 个答案:

没有答案