渲染道具 - 反应路线
Render Props - React Route
const Home = () => <div>Home</div>
const App = () => {
const someVariable = true;
return (
<Switch>
{/* these are good */}
<Route exact path='/' component={Home} />
<Route
path='/about'
render={(props) => <About {...props} />}
/>
</Switch>
)
}
const About = (props) => {
return (
<div>
About
</div>
)
}
在代码示例中,在
<Route
path='/about'
render={(props) => <About {...props} />}
/>
当react遇到作为react-router一部分的Route组件的render prop时,它传递的props是什么?
根据 https://reactjs.org/docs/render-props.html 的文档,
render prop 是组件用来知道要渲染什么的函数 prop,
值是通过埋在 react-router
中 Route 声明中的道具传递的吗
路由组件将 props 传递给 render prop 方法。您可以在 React Router 源代码中看到这一点。 Route 组件传递的 props 有 match, location, history, staticContext
。如果你想使用来自父组件的道具,你正在定义渲染道具方法,那么你可以省略道具参数。
render={() => <About {...props} />}
然后你将从包含路由的组件中获取道具。
您提供的示例没有多大意义,因为它复制了您通过在 Route 上使用 'component' 道具获得的行为。
在渲染方法中传递道具时,你会得到反应路由器默认道具,就像使用 component
而不是使用隐式获得所有这些道具匹配、位置、历史和 staticContext 的渲染道具。并且您需要提供 props 作为参数,否则 render 方法不会将 props 传递给 children 因为它会认为它未定义。
这是在 React 路由器中渲染道具的工作示例:
https://codesandbox.io/s/72k8xz669j
我们将 Route 与渲染道具一起使用,
<Route path = "/about" component={About} />
或者,
<Route path = "/about" render= { (props) => <About {...props} } />
第二个与第一个的不同之处在于,在第二种情况下,About 组件可以访问通过 Route 传入的道具。
比如说,
有一个配置文件组件,
<Route path="/admin/profile"
render={ props => (
<Profile tabs= {"valuePassed"} {...props} />
)}
/>
现在在 Profile 组件中,我们可以访问所有的 props,
this.props.tabs 在基于 class 的组件中给出 "valuePasses" 而 props.tabs 用于功能组件。
希望对您有所帮助。
const Home = () => <div>Home</div>
const App = () => {
const someVariable = true;
return (
<Switch>
{/* these are good */}
<Route exact path='/' component={Home} />
<Route
path='/about'
render={(props) => <About {...props} />}
/>
</Switch>
)
}
const About = (props) => {
return (
<div>
About
</div>
)
}
在代码示例中,在
<Route
path='/about'
render={(props) => <About {...props} />}
/>
当react遇到作为react-router一部分的Route组件的render prop时,它传递的props是什么?
根据 https://reactjs.org/docs/render-props.html 的文档, render prop 是组件用来知道要渲染什么的函数 prop, 值是通过埋在 react-router
中 Route 声明中的道具传递的吗路由组件将 props 传递给 render prop 方法。您可以在 React Router 源代码中看到这一点。 Route 组件传递的 props 有 match, location, history, staticContext
。如果你想使用来自父组件的道具,你正在定义渲染道具方法,那么你可以省略道具参数。
render={() => <About {...props} />}
然后你将从包含路由的组件中获取道具。
您提供的示例没有多大意义,因为它复制了您通过在 Route 上使用 'component' 道具获得的行为。
在渲染方法中传递道具时,你会得到反应路由器默认道具,就像使用 component
而不是使用隐式获得所有这些道具匹配、位置、历史和 staticContext 的渲染道具。并且您需要提供 props 作为参数,否则 render 方法不会将 props 传递给 children 因为它会认为它未定义。
这是在 React 路由器中渲染道具的工作示例: https://codesandbox.io/s/72k8xz669j
我们将 Route 与渲染道具一起使用,
<Route path = "/about" component={About} />
或者,
<Route path = "/about" render= { (props) => <About {...props} } />
第二个与第一个的不同之处在于,在第二种情况下,About 组件可以访问通过 Route 传入的道具。
比如说, 有一个配置文件组件,
<Route path="/admin/profile"
render={ props => (
<Profile tabs= {"valuePassed"} {...props} />
)}
/>
现在在 Profile 组件中,我们可以访问所有的 props,
this.props.tabs 在基于 class 的组件中给出 "valuePasses" 而 props.tabs 用于功能组件。
希望对您有所帮助。