reactjs - 将 const 函数转换为组件
问题描述
我正在尝试将这行代码转换为组件。这行代码有效:
const GlobalCss = withStyles(s)(() => null);
export default GlobalCss;
这是它作为组件的样子:
const GlobalCss = function(props){
return withStyles(props.css)(() => null);
}
但这会产生错误:
对象作为 React 子对象无效
解决方案
这可能与material-ui
withStyle
HOC的问题有关
对于您的代码
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)));
你可以在这里在线尝试
更新
如果需求需要通过classes
完成props
使用withStyles
就足够了
interface Props extends WithStyles<typeof styles> {
classes: any,
...
更新 V.2
如果你想同时使用全局样式withStyles
,可以选择在withStyles
.
export const YourComponent = withStyles()(
mergeGlobalStylesHOC(() => null)
);
更新 V.3
对于功能组件,导出全局样式钩子也是一个好习惯。
如果你想自定义所有的材质组件而不需要到处写相关的样式,那么简单地重用自定义的组件会很好。
推荐阅读
- python - Related_name 从 Django 表单返回属性错误 (NoneType)。我正在尝试在表单中创建一个动态过滤器
- c++ - 在“0”参数上强制编译错误(C++)
- node.js - 数组属性上的“updateMany”和“$pull”问题
- checkbox - 通过 JSXGraph 中的复选框可见的元素:更改其他参数?
- mobile - 在放大的图像窗口中手动放大
- mysql - MYSQL 从旧日期计算当前年份的第 1 个月、第 2 个月等
- kubernetes - kubernetes dns 列出服务的所有 ip
- python - 将多索引数据框中的多列加在一起,然后将列与结果相加
- typescript - useIonViewWillEnter 在重新进入页面时具有状态变量的默认值
- javascript - 使用 Jquery DataTable 进行分页时,Bootstrap 切换消失