reactjs - 为什么 React 不能识别传递给另一个组件的函数?
问题描述
我有一个父组件,我在其中创建了这个函数,该函数被传递给另一个组件:
export default withRouter(({ history }) => {
const selectedRouteStyle = currentPath => {
if (history.location.pathname === currentPath) {
return {
color: '#565958',
fontWeight: '700',
borderBottom: '2px solid #4292ff',
}
} else {
return {
color: '#989e9c',
}
}
};
return (
<Child
selectedRouteStyle={selectedRouteStyle}
/>
);
});
在子组件中,我像这样引用 selectedRouteStyle:
<Link
to="/profile/chronology"
className="App_profile_navigation_link"
style={selectedRouteStyle('/profile/chronology')}
>
Chronology
</Link>
据我所知,它应该可以正常工作,但是我收到了这个错误:
TypeError: selectedRouteStyle is not a function
我怎样才能让反应识别这个功能?
解决方案
如果你使用的是类组件,你应该使用this.props.selectedRouteStyle('/profile/chronology')
,如果你使用的是函数组件,你需要使用props.selectedRouteStyle('/profile/chronology')
推荐阅读
- heroku - 将 Heroku Postgres 数据库暴露给外部应用程序
- html - div p { margin-bottom: 10px;} 不工作
- python - 确定日期时间是否在工作日计划内
- python - 熊猫移动平均交叉回测中的错误
- exchangewebservices - EWS managed-api 在导入 EML 时遇到 500 内部服务器错误
- maven - 我得到 LEAK: ByteBuf.release() 在垃圾收集之前没有被调用。见 http://netty.io/wiki/reference-counted-objects.html
- c - 在我自己的元层上加载我自己的设备驱动程序作为 Yocto 的内置驱动程序
- ios - Moya 和 Alamofire 奇怪的超时错误
- java - 在 Java 中使用 XPath 和 Saxon 获取源文档中的行号,而不是转换后的文档
- python - 没有{}的python字符串格式