绿叶虫 發表於 2020-12-3 09:15:00

react-router-dom基本使用+3种传参方式

<pre><code class="language-javascript">//App.js
import {
BrowserRouter as Router,
Route,
Link,
} from "react-router-dom";
// 引入组件
import Home from "....";
import News from "...."
function App() {
return (
    &lt;Router&gt;
      &lt;Link to="/"&gt;首页&lt;/Link&gt;
      &lt;Link to="/news"&gt;新闻&lt;/Link&gt;
      &lt;Route exact path="/" component={Home} /&gt;
      &lt;Route path="/news" component={News} /&gt;   
    &lt;/Router&gt;
);
}
export defautl App;
</code></pre>
<h2 id="如何传递参数3种">如何传递参数(3种)</h2>
<h3 id="1params传参动态路由">1、params传参(动态路由)</h3>
<p>特点:刷新页面参数不消失,参数会在地址栏显示</p>
<ul>
<li>路由配置</li>
</ul>
<pre><code class="language-html">&lt;Route path='/about/:id' component={About} /&gt;
</code></pre>
<ul>
<li>跳转方式</li>
</ul>
<pre><code class="language-js">//传递参数可以拆分为对象写法:{pathname:'/about/3'}
//html:
&lt;Link to={'/about/3'}&gt;点击跳转&lt;/Link&gt;
//js:
this.props.history.push('/about/3')
</code></pre>
<ul>
<li>获取值</li>
</ul>
<pre><code class="language-js">this.props.match.params.id// 3
</code></pre>
<h3 id="2query传参">2、query传参</h3>
<p>特点:刷新页面参数消失,参数不会在地址栏显示</p>
<ul>
<li>路由配置</li>
</ul>
<pre><code class="language-html">&lt;Route path='/about' component={About} /&gt;
</code></pre>
<ul>
<li>跳转方式</li>
</ul>
<pre><code class="language-js">//html:
&lt;Link to={{pathname:'/about', query:{id:3}}}&gt;点击跳转&lt;/Link&gt;
//js:
this.props.history.push({pathname:'/about', query:{id:3}})
</code></pre>
<ul>
<li>获取值</li>
</ul>
<pre><code class="language-js">this.props.location.query.id// 3
</code></pre>
<h3 id="3state传参">3、state传参</h3>
<p>特点:刷新页面参数不消失,参数不会在地址栏显示</p>
<ul>
<li>路由配置</li>
</ul>
<pre><code class="language-html">&lt;Route path='/about' component={About} /&gt;
</code></pre>
<ul>
<li>跳转方式</li>
</ul>
<pre><code class="language-js">//html:
&lt;Link to={{pathname:'/about', state:{id:3}}}&gt;点击跳转&lt;/Link&gt;
//js:
this.props.history.push({pathname:'/about', state:{id:3}})
</code></pre>
<ul>
<li>获取值</li>
</ul>
<pre><code class="language-js">this.props.location.state.id// 3
</code></pre><br><br>
来源:https://www.cnblogs.com/sgs123/p/14077680.html
頁: [1]
查看完整版本: react-router-dom基本使用+3种传参方式