首页 > 解决方案 > 为什么 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

我怎样才能让反应识别这个功能?

标签: reactjstypeerrorreact-props

解决方案


如果你使用的是类组件,你应该使用this.props.selectedRouteStyle('/profile/chronology'),如果你使用的是函数组件,你需要使用props.selectedRouteStyle('/profile/chronology')


推荐阅读