Routing to specific part of other component in React

你说的曾经没有我的故事 提交于 2020-01-25 06:51:05

问题


I have a problem with routing to a specific part of another functional component in React. I have declared Route in Main component and Link around the place where I want to redirect from... it looks like this... The main function gets:

<Switch>
    <Route exact path='/news/:eyof' component={News} />
    <Route exact path='/news/:svetsko' component={News} />
    <Route exact path='/news' component={News} />
</Switch>

And I defined in other functional component:

<div className="card">
  <Link to="/news/:svetsko">
    <div className="card-header">
      <h3>Artistic gymnastics world championship</h3>
     </div>
   </Link>
</div>

So by clicking on this link, I need to get redirected to News page class "svetsko" so I can read about that news... All news are in containers in same page....


回答1:


You need only one route like

<Switch>
    <Route exact path='/news' component={News} />
</Switch>

you can give link like

 <Link to={{
  pathname: '/news',
  state: { news : yourNewsName } // you can pass svetsko here
}}> 

 <div className="card-header">
  <h3>Artistic gymnastics world championship</h3>
 </div>

</Link>

You can access this state in your News Page like

<div>{  props.location.state !== undefined ? props.location.state.news : '' }</div>

After getting your news type like eyof :

Step 1 :

   you can create on functional component which takes argument as your
 data and return your new post jsx with your data.

Step2 :

   So,when you get your eyof in your page then you are going to call 
this function and pass your data related to your eyof and that function 
return your new post to your page.



回答2:


Try something like this in your component:

let { scrollToSection } = useParams();
svetskoRef = React.createRef();

useParams() allows you to access :svetsko. When the component loads, you can use scrollToSection to navigate between different parts of the page. The scrollRef is used to access the DOM element you want to scroll to.

window.scrollTo(0,scrollRef.offsetTop)

The markup would look something like this:

<div className="card" ref="svetskoRef">
  <Link to="/news/:svetsko">
    <div className="card-header">
      <h3>Artistic gymnastics world championship</h3>
     </div>
   </Link>
</div>


来源:https://stackoverflow.com/questions/59771012/routing-to-specific-part-of-other-component-in-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!