无法通过react-router的render方法向组件传递自定义函数prop的问题
问题原因
- 子组件取值方式错误
传入组件的自定义属性全部挂载在组件的props对象上,你直接在子组件内执行console.log(validateAuthOnAction)是访问当前作用域的同名变量,没有从props中读取,自然返回undefined。 - React Router版本不兼容/属性优先级冲突
- 如果你使用的是React Router v6及以上版本,官方已经废弃了
render、component属性,仅支持element属性传入组件,你写的render回调根本不会执行,属性自然传递失败。 - 如果你使用的是React Router v5及以下版本,Route组件的属性优先级为
children>component>render,如果传入PrivateRoute的props中自带children属性,你自定义的render回调会被覆盖,不会执行。
解决方案
- 修正子组件的取值逻辑
函数组件需要先接收props参数,再从props中读取属性:
// 函数组件写法 const TargetComponent = (props) => { // 正确读取方式 console.log(props.validateAuthOnAction) // 也可以提前解构 // const { validateAuthOnAction } = props return <div>目标组件</div> }
类组件从this.props中读取属性:
// 类组件写法 class TargetComponent extends React.Component { componentDidMount() { console.log(this.props.validateAuthOnAction) } render() { return <div>目标组件</div> } }
- 适配React Router版本
如果是v6及以上版本,替换为element属性传值:
return ( <Route {...props} element={<Component validateAuthOnAction={validateAuthOnAction} />} /> )
如果是v5及以下版本,确保传入的props中没有children属性,同时可以透传路由自带的props:
return ( <Route {...props} render={(routeProps) => <Component {...routeProps} validateAuthOnAction={validateAuthOnAction} />} /> )
内容的提问来源于stack exchange,提问作者Yasas Nanayakkara
相关产品推荐
相关产品推荐

