将参数传递给动态生成的反应路线
Passing parameters to dynamically generated react routes
我正在使用 react-router-dom
并从这样的数组中动态生成我的路线
路由数据
const routes = [
{
path: '/',
exact: true,
component: () => <MyComponent />
}
}
路由生成
{routes.map((route, index) => {
return <Route
key={index}
path={route.path}
exact={route.exact}
component={route.component}
/>
})}
渲染道具
我发现了我可以定义的 render() 道具,但即便如此我该怎么做,因为组件在一个变量中
const props = this.props;
{routes.map((route, index) => {
return <Route
key={index}
path={route.path}
exact={route.exact}
render={(props) => <??? {...props} />
/>
})}
如何在路由生成过程中传递this.props?
您可以更改数组以仅包含组件而不是呈现组件的新功能组件,您将获得发送给它的道具:
const routes = [
{
path: '/',
exact: true,
component: MyComponent
}
}
您可以使用任何大写变量作为组件,因此如果您愿意,也可以这样做:
{routes.map((route, index) => {
const Component = route.component;
return <Route
key={index}
path={route.path}
exact={route.exact}
render={(props) => <Component {...props} />
/>
})}
我正在使用 react-router-dom
并从这样的数组中动态生成我的路线
路由数据
const routes = [
{
path: '/',
exact: true,
component: () => <MyComponent />
}
}
路由生成
{routes.map((route, index) => {
return <Route
key={index}
path={route.path}
exact={route.exact}
component={route.component}
/>
})}
渲染道具 我发现了我可以定义的 render() 道具,但即便如此我该怎么做,因为组件在一个变量中
const props = this.props;
{routes.map((route, index) => {
return <Route
key={index}
path={route.path}
exact={route.exact}
render={(props) => <??? {...props} />
/>
})}
如何在路由生成过程中传递this.props?
您可以更改数组以仅包含组件而不是呈现组件的新功能组件,您将获得发送给它的道具:
const routes = [
{
path: '/',
exact: true,
component: MyComponent
}
}
您可以使用任何大写变量作为组件,因此如果您愿意,也可以这样做:
{routes.map((route, index) => {
const Component = route.component;
return <Route
key={index}
path={route.path}
exact={route.exact}
render={(props) => <Component {...props} />
/>
})}