在Reaction-路由器v4中将自定义道具传递给路由器组件我正在使用Reaction路由器创建一个多页面应用程序。我的主要组成部分是<App/>它呈现到子组件的所有路由。我试图通过路线传递道具,并根据一些研究我这样做了,子组件最常用的方式是通过this.props.route对象,它们继承。但是,对于我来说,这个对象是未定义的。我的render()函数在子组件中,iconsole.log(this.props)返回一个像这样的对象{match: Object, location: Object, history: Object, staticContext: undefined}一点都不像我所期望的道具。这是我的详细代码。父组件(我试图在我的所有子组件中传递单词“hi”作为一个名为“test”的支柱):import { BrowserRouter as Router, HashRouter, Route, Switch } from 'react-router-dom';import Link from 'react-router';
import React from 'react';import Home from './Home.jsx';import Nav from './Nav.jsx';import Progress from './Progress.jsx';
import Test from './Test.jsx';export default class App extends React.Component {
constructor() {
super();
this._fetchPuzzle = this._fetchPuzzle.bind(this);
}
render() {
return (
<Router>
<div>
<Nav />
<Switch>
<Route path="/" exact test="hi" component={Home} />
<Route path="/progress" test="hi" component={Progress} />
<Route path="/test" test="hi" component={Test} />
<Route render={() => <p>Page not found!</p>} />
</Switch>
</div>
</Router>
);
}}儿童:import React from 'react';const CodeMirror = require('react-codemirror');import { Link } from 'react-router-dom';
require('codemirror/mode/javascript/javascript')require('codemirror/mode/xml/xml');require('codemirror/mode/markdown/markdown');
export default class Home extends React.Component {
constructor(props) {
super(props);
console.log(props)
}
render() {
const options = {
lineNumbers: true,
theme: 'abcdef'
// mode: this.state.mode
};
console.log(this.props)
return (
<div>
<h1>First page bro</h1>
<CodeMirror value='code lol' onChange={()=>'do something'} options={options} />
</div>);
}}我对此反应很新,所以如果我错过了一些显而易见的事情,我很抱歉。谢谢!
3 回答
FFIVE
TA贡献1797条经验 获得超6个赞
render
Route
这允许方便的内联呈现和包装,而不需要上述不想要的重新安装。 component
属性时,可以传入要调用的函数。 location
火柴。呈现道具接收所有与组件呈现道具相同的路由道具。
<Route path="/" exact render={(props) => (<Home test="hi" {...props}/>)} />
this.props.test
Home
P.S.
也要确保你是经过 {...props}
这样,默认的路由器道具就像 location, history, match etc
也被传递到 Home
组件,否则,传递给它的唯一支柱是 test
.
慕丝7291255
TA贡献1859条经验 获得超6个赞
render()
海绵宝宝撒
TA贡献1809条经验 获得超8个赞
您应该将props参数添加到传入的函数中,并将其与{.props}一起在组件‘home’中使用,否则您将失去标准的支持-Reaction路由器V4传入
添加回答
举报
0/150
提交
取消