首页 > 解决方案 > 将 const 函数转换为组件

问题描述

我正在尝试将这行代码转换为组件。这行代码有效:

const GlobalCss = withStyles(s)(() => null);
export default GlobalCss;

这是它作为组件的样子:

const GlobalCss = function(props){
    return withStyles(props.css)(() => null);
}

但这会产生错误:

对象作为 React 子对象无效

标签: reactjs

解决方案


这可能与material-ui withStyleHOC的问题有关

对于您的代码

const App = function(props){
    return withStyles()(() => null);
}

和下面的一样arrow function version

const App = props => withStyles()(() => null); // Nop

这有效

const App = withStyles()(() => null); // OK

所以如果你需要props被定义,在风格相关的HOC里面使用它似乎没问题。

const App = withStyles()(props => null); // OK

在我们的 prod 中,我们也使用了其他redux connect与 props inside 相关的HOC withStyles

样本:

export const ComponentName = withTheme(withStyles(styles)(connect(
  (store: Store) => ({...}), // props
  (dispatch: any) => ({...}) // props
)(YourComponent)));

你可以在这里在线尝试

编辑happy-snowflake-9t4p7

更新

如果需求需要通过classes完成props

使用withStyles就足够了

interface Props extends WithStyles<typeof styles> {
  classes: any,
  ...

更新 V.2

如果你想同时使用全局样式withStyles,可以选择在withStyles.

export const YourComponent = withStyles()(
  mergeGlobalStylesHOC(() => null)
);

更新 V.3

对于功能组件,导出全局样式钩子也是一个好习惯。

如果你想自定义所有的材质组件而不需要到处写相关的样式,那么简单地重用自定义的组件会很好。


推荐阅读