Mar*_*ano 16 javascript reactjs react-router react-router-v4
我正在使用React Router创建一个多页面应用程序.我的主要组件是<App/>
,它将所有路由转换为子组件.我正试图通过路线传递道具,并且基于我所做的一些研究,子组件最常用的方式是传递到传递的道具是通过this.props.route
它们继承的对象.但是,这个对象对我来说是不确定的.在我render()
的子组件中的函数中,我将console.log(this.props)
返回一个看起来像这样的对象
{match: Object, location: Object, history: Object, staticContext: undefined}
Run Code Online (Sandbox Code Playgroud)
看起来不像我期望的道具.这是我的详细代码.
父组件(我试图在我的所有子组件中将"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>
);
}
}
Run Code Online (Sandbox Code Playgroud)
儿童:
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>);
}
}
Run Code Online (Sandbox Code Playgroud)
我对React很新,所以如果我错过了一些明显的东西我会道歉.谢谢!
Shu*_*tri 28
您可以通过使用render
prop来将props传递给组件Route
,从而内联组件定义.根据DOCS:
这允许方便的内联呈现和包装,而不需要上面解释的不期望的重新安装.不使用
component
prop 为您创建新的React元素,您可以传入一个函数,以便在location
匹配时调用.渲染道具接收与组件渲染道具相同的所有路径道具
所以你可以把道具传递给像这样的组件
<Route path="/" exact render={(props) => (<Home test="hi" {...props}/>)} />
Run Code Online (Sandbox Code Playgroud)
然后你可以像访问它一样访问它
this.props.test
Run Code Online (Sandbox Code Playgroud)
在您的Home
组件中
PS还要确保你正在传递,
{...props}
以便默认的路由器道具location, history, match etc
也被传递给Home
组件,否则唯一的传递给它的道具是test
.
归档时间: |
|
查看次数: |
13209 次 |
最近记录: |