Javascript 在 Link react-router 中传递道具
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30115324/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pass props in Link react-router
提问by vishal atmakuri
I am using react with react-router. I am trying to pass property's in a "Link" of react-router
我正在使用 react-router 进行反应。我正在尝试在 react-router 的“链接”中传递属性
var React = require('react');
var Router = require('react-router');
var CreateIdeaView = require('./components/createIdeaView.jsx');
var Link = Router.Link;
var Route = Router.Route;
var DefaultRoute = Router.DefaultRoute;
var RouteHandler = Router.RouteHandler;
var App = React.createClass({
render : function(){
return(
<div>
<Link to="ideas" params={{ testvalue: "hello" }}>Create Idea</Link>
<RouteHandler/>
</div>
);
}
});
var routes = (
<Route name="app" path="/" handler={App}>
<Route name="ideas" handler={CreateIdeaView} />
<DefaultRoute handler={Home} />
</Route>
);
Router.run(routes, function(Handler) {
React.render(<Handler />, document.getElementById('main'))
});
The "Link" renders the page but does not pass the property to the new view. Below is the view code
“链接”呈现页面但不将属性传递给新视图。下面是查看代码
var React = require('react');
var Router = require('react-router');
var CreateIdeaView = React.createClass({
render : function(){
console.log('props form link',this.props,this)//props not recived
return(
<div>
<h1>Create Post: </h1>
<input type='text' ref='newIdeaTitle' placeholder='title'></input>
<input type='text' ref='newIdeaBody' placeholder='body'></input>
</div>
);
}
});
module.exports = CreateIdeaView;
How can I pass data using "Link"?
如何使用“链接”传递数据?
采纳答案by jmunsch
This line is missing path:
缺少这一行path:
<Route name="ideas" handler={CreateIdeaView} />
Should be:
应该:
<Route name="ideas" path="/:testvalue" handler={CreateIdeaView} />
Given the following Link(outdated v1):
鉴于以下Link(过时的 v1):
<Link to="ideas" params={{ testvalue: "hello" }}>Create Idea</Link>
Up to date as of v4:
最新的 v4:
const backUrl = '/some/other/value'
// this.props.testvalue === "hello"
<Link to={{pathname: `/${this.props.testvalue}`, query: {backUrl}}} />
and in the withRouter(CreateIdeaView)components render():
并在withRouter(CreateIdeaView)组件中render():
console.log(this.props.match.params.testvalue, this.props.location.query.backurl)
// output
hello /some/other/value
From the link that you posted on the docs, towards the bottom of the page:
从您在文档上发布的链接到页面底部:
Given a route like
<Route name="user" path="/users/:userId"/>
给定一条路线
<Route name="user" path="/users/:userId"/>
Updated code example with some stubbed query examples:
使用一些存根查询示例更新了代码示例:
// import React, {Component, Props, ReactDOM} from 'react';
// import {Route, Switch} from 'react-router'; etc etc
// this snippet has it all attached to window since its in browser
const {
BrowserRouter,
Switch,
Route,
Link,
NavLink
} = ReactRouterDOM;
class World extends React.Component {
constructor(props) {
super(props);
console.dir(props);
this.state = {
fromIdeas: props.match.params.WORLD || 'unknown'
}
}
render() {
const { match, location} = this.props;
return (
<React.Fragment>
<h2>{this.state.fromIdeas}</h2>
<span>thing:
{location.query
&& location.query.thing}
</span><br/>
<span>another1:
{location.query
&& location.query.another1
|| 'none for 2 or 3'}
</span>
</React.Fragment>
);
}
}
class Ideas extends React.Component {
constructor(props) {
super(props);
console.dir(props);
this.state = {
fromAppItem: props.location.item,
fromAppId: props.location.id,
nextPage: 'world1',
showWorld2: false
}
}
render() {
return (
<React.Fragment>
<li>item: {this.state.fromAppItem.okay}</li>
<li>id: {this.state.fromAppId}</li>
<li>
<Link
to={{
pathname: `/hello/${this.state.nextPage}`,
query:{thing: 'asdf', another1: 'stuff'}
}}>
Home 1
</Link>
</li>
<li>
<button
onClick={() => this.setState({
nextPage: 'world2',
showWorld2: true})}>
switch 2
</button>
</li>
{this.state.showWorld2
&&
<li>
<Link
to={{
pathname: `/hello/${this.state.nextPage}`,
query:{thing: 'fdsa'}}} >
Home 2
</Link>
</li>
}
<NavLink to="/hello">Home 3</NavLink>
</React.Fragment>
);
}
}
class App extends React.Component {
render() {
return (
<React.Fragment>
<Link to={{
pathname:'/ideas/:id',
id: 222,
item: {
okay: 123
}}}>Ideas</Link>
<Switch>
<Route exact path='/ideas/:id/' component={Ideas}/>
<Route path='/hello/:WORLD?/:thing?' component={World}/>
</Switch>
</React.Fragment>
);
}
}
ReactDOM.render((
<BrowserRouter>
<App />
</BrowserRouter>
), document.getElementById('ideas'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-router-dom/4.3.1/react-router-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-router/4.3.1/react-router.min.js"></script>
<div id="ideas"></div>
updates:
更新:
参见:https: //github.com/ReactTraining/react-router/blob/0c6d51cd6639aff8a84b11d89e27887b3558ed8a/upgrade-guides/v2.0.0.md#link-to-onenter-and-isactive-use-location-descriptors
From the upgrade guide from 1.x to 2.x:
<Link to>, onEnter, and isActive use location descriptors
<Link to>can now take a location descriptor in addition to strings. The query and state props are deprecated.// v1.0.x
<Link to="/foo" query={{ the: 'query' }}/>// v2.0.0
<Link to={{ pathname: '/foo', query: { the: 'query' } }}/>// Still valid in 2.x
<Link to="/foo"/>Likewise, redirecting from an onEnter hook now also uses a location descriptor.
// v1.0.x
(nextState, replaceState) => replaceState(null, '/foo') (nextState, replaceState) => replaceState(null, '/foo', { the: 'query' })// v2.0.0
(nextState, replace) => replace('/foo') (nextState, replace) => replace({ pathname: '/foo', query: { the: 'query' } })For custom link-like components, the same applies for router.isActive, previously history.isActive.
// v1.0.x
history.isActive(pathname, query, indexOnly)// v2.0.0
router.isActive({ pathname, query }, indexOnly)
从 1.x 到 2.x 的升级指南:
<Link to>、 onEnter 和 isActive 使用位置描述符
<Link to>除了字符串之外,现在还可以使用位置描述符。不推荐使用查询和状态道具。// v1.0.x
<Link to="/foo" query={{ the: 'query' }}/>// v2.0.0
<Link to={{ pathname: '/foo', query: { the: 'query' } }}/>// 在 2.x 中仍然有效
<Link to="/foo"/>同样,从 onEnter 钩子重定向现在也使用位置描述符。
// v1.0.x
(nextState, replaceState) => replaceState(null, '/foo') (nextState, replaceState) => replaceState(null, '/foo', { the: 'query' })// v2.0.0
(nextState, replace) => replace('/foo') (nextState, replace) => replace({ pathname: '/foo', query: { the: 'query' } })对于自定义类似链接的组件,同样适用于 router.isActive,以前的 history.isActive。
// v1.0.x
history.isActive(pathname, query, indexOnly)// v2.0.0
router.isActive({ pathname, query }, indexOnly)
updates for v3 to v4:
v3 到 v4 的更新:
- https://github.com/ReactTraining/react-router/pull/3669
- https://github.com/ReactTraining/react-router/pull/3430
- https://github.com/ReactTraining/react-router/pull/3443
- https://github.com/ReactTraining/react-router/pull/3803
- https://github.com/ReactTraining/react-router/pull/3636
- https://github.com/ReactTraining/react-router/pull/3397
https://github.com/ReactTraining/react-router/pull/3288
The interface is basically still the same as v2, best to look at the CHANGES.md for react-router, as that is where the updates are.
- https://github.com/ReactTraining/react-router/pull/3669
- https://github.com/ReactTraining/react-router/pull/3430
- https://github.com/ReactTraining/react-router/pull/3443
- https://github.com/ReactTraining/react-router/pull/3803
- https://github.com/ReactTraining/react-router/pull/3636
- https://github.com/ReactTraining/react-router/pull/3397
https://github.com/ReactTraining/react-router/pull/3288
界面基本上还是和 v2 一样,最好查看 react-router 的 CHANGES.md,因为那是更新的地方。
"legacy migration documentation" for posterity
子孙后代的“遗留移民文件”
- https://github.com/ReactTraining/react-router/blob/dc7facf205f9ee43cebea9fab710dce036d04f04/packages/react-router/docs/guides/migrating.md
- https://github.com/ReactTraining/react-router/blob/0c6d51cd6639aff8a84b11d89e27887b3558ed8a/upgrade-guides/v1.0.0.md
- https://github.com/ReactTraining/react-router/blob/0c6d51cd6639aff8a84b11d89e27887b3558ed8a/upgrade-guides/v2.0.0.md
- https://github.com/ReactTraining/react-router/blob/0c6d51cd6639aff8a84b11d89e27887b3558ed8a/upgrade-guides/v2.2.0.md
- https://github.com/ReactTraining/react-router/blob/0c6d51cd6639aff8a84b11d89e27887b3558ed8a/upgrade-guides/v2.4.0.md
- https://github.com/ReactTraining/react-router/blob/0c6d51cd6639aff8a84b11d89e27887b3558ed8a/upgrade-guides/v2.5.0.md
- https://github.com/ReactTraining/react-router/blob/dc7facf205f9ee43cebea9fab710dce036d04f04/packages/react-router/docs/guides/migrating.md
- https://github.com/ReactTraining/react-router/blob/0c6d51cd6639aff8a84b11d89e27887b3558ed8a/upgrade-guides/v1.0.0.md
- https://github.com/ReactTraining/react-router/blob/0c6d51cd6639aff8a84b11d89e27887b3558ed8a/upgrade-guides/v2.0.0.md
- https://github.com/ReactTraining/react-router/blob/0c6d51cd6639aff8a84b11d89e27887b3558ed8a/upgrade-guides/v2.2.0.md
- https://github.com/ReactTraining/react-router/blob/0c6d51cd6639aff8a84b11d89e27887b3558ed8a/upgrade-guides/v2.4.0.md
- https://github.com/ReactTraining/react-router/blob/0c6d51cd6639aff8a84b11d89e27887b3558ed8a/upgrade-guides/v2.5.0.md
回答by Chetan Sisodiya
there is a way you can pass more than one parameter. You can pass "to" as object instead of string.
有一种方法可以传递多个参数。您可以将“to”作为对象而不是字符串传递。
// your route setup
<Route path="/category/:catId" component={Category} / >
// your link creation
const newTo = {
pathname: "/category/595212758daa6810cbba4104",
param1: "Par1"
};
// link to the "location"
// see (https://reacttraining.com/react-router/web/api/location)
<Link to={newTo}> </Link>
// In your Category Component, you can access the data like this
this.props.match.params.catId // this is 595212758daa6810cbba4104
this.props.location.param1 // this is Par1
回答by Alessander Fran?a
I had the same problem to show an user detail from my application.
我在显示应用程序中的用户详细信息时遇到了同样的问题。
You can do this:
你可以这样做:
<Link to={'/ideas/'+this.props.testvalue }>Create Idea</Link>
or
或者
<Link to="ideas/hello">Create Idea</Link>
and
和
<Route name="ideas/:value" handler={CreateIdeaView} />
to get this via this.props.match.params.valueat your CreateIdeaView class.
通过this.props.match.params.value在您的 CreateIdeaView 类中获取此信息。
You can see this video that helped me a lot: https://www.youtube.com/watch?v=ZBxMljq9GSE
你可以看到这个对我有很大帮助的视频:https: //www.youtube.com/watch?v=ZBxMljq9GSE
回答by Kevin K.
as for react-router-dom 4.x.x (https://www.npmjs.com/package/react-router-dom) you can pass params to the component to route to via:
至于 react-router-dom 4.xx ( https://www.npmjs.com/package/react-router-dom),您可以将参数传递给组件以通过以下方式路由:
<Route path="/ideas/:value" component ={CreateIdeaView} />
linking via (considering testValue prop is passed to the corresponding component (e.g. the above App component) rendering the link)
链接通过(考虑 testValue prop 被传递到渲染链接的相应组件(例如上面的 App 组件))
<Link to={`/ideas/${ this.props.testValue }`}>Create Idea</Link>
passing props to your component constructor the value param will be available via
将道具传递给您的组件构造函数,值参数将通过
props.match.params.value
回答by Farhan
The simple is that:
简单的是:
<Link to={{
pathname: `your/location`,
state: {send anything from here}
}}
Now you want to access it:
现在你想访问它:
this.props.location.state
回答by Krishna Kumar Jangid
After install react-router-dom
安装后 react-router-dom
<Link
to={{
pathname: "/product-detail",
productdetailProps: {
productdetail: "I M passed From Props"
}
}}>
Click To Pass Props
</Link>
and other end where the route is redirected do this
路由重定向的另一端执行此操作
componentDidMount() {
console.log("product props is", this.props.location.productdetailProps);
}
回答by FBaez51
To work off the answer above (https://stackoverflow.com/a/44860918/2011818), you can also send the objects inline the "To" inside the Link object.
要解决上面的答案(https://stackoverflow.com/a/44860918/2011818),您还可以将对象内联发送到链接对象内的“收件人”。
<Route path="/foo/:fooId" component={foo} / >
<Link to={{pathname:/foo/newb, sampleParam: "Hello", sampleParam2: "World!" }}> CLICK HERE </Link>
this.props.match.params.fooId //newb
this.props.location.sampleParam //"Hello"
this.props.location.sampleParam2 //"World!"
回答by gprathour
Typescript
打字稿
For approach mentioned like this in many answers,
对于许多答案中提到的方法,
<Link
to={{
pathname: "/my-path",
myProps: {
hello: "Hello World"
}
}}>
Press Me
</Link>
I was getting error,
我收到错误,
Object literal may only specify known properties, and 'myProps' does not exist in type 'LocationDescriptorObject | ((location: Location) => LocationDescriptor)'
对象字面量只能指定已知的属性,而 'myProps' 不存在于类型 'LocationDescriptorObject | 中。((位置:位置) => LocationDescriptor)'
Then I checked in the official documentationthey have provided statefor the same purpose.
然后我检查了他们为相同目的提供的官方文档state。
So it worked like this,
所以它是这样工作的,
<Link
to={{
pathname: "/my-path",
state: {
hello: "Hello World"
}
}}>
Press Me
</Link>
And in your next component you can get this value as following,
在您的下一个组件中,您可以获得以下值,
componentDidMount() {
console.log("received "+this.props.location.state.hello);
}
回答by Abu Shumon
Route:
路线:
<Route state={this.state} exact path="/customers/:id" render={(props) => <PageCustomer {...props} state={this.state} />} />
And then can access params in your PageCustomer component like this: this.props.match.params.id.
然后就可以在你这样的PageCustomer组件访问PARAMS: this.props.match.params.id。
For example an api call in PageCustomer component:
例如 PageCustomer 组件中的 api 调用:
axios({
method: 'get',
url: '/api/customers/' + this.props.match.params.id,
data: {},
headers: {'X-Requested-With': 'XMLHttpRequest'}
})

