javascript - withSyles HOC 在通过 React.forwardRef 时不会将 innerRef 与其他道具一起传递
问题描述
我将使用的 ref 传递React.forwardRef
给通常有效的向下组件。
<SomeComponent
component={React.forwardRef((props, ref) => <MyComponent innerRef={ref} {...props} />)}
.../>
但是,当我使用带有样式的 HOC(高阶组件)时,innerRef 以及其他道具无法正确传递。
// innerRef does not exists in props
const MyComponent = withStyles(styles)(({ one, two, ...props }) => {
return (
<Fragment>
<NavLink {...props}></NavLink>
...
</Fragment>
);
})
不使用 withStyles 我可以完美地得到它们
// innerRef exists in props
const MyComponent = ({ one, two, ...props }) => {
return (
<Fragment>
<NavLink {...props}></NavLink>
...
</Fragment>
);
}
我怎样才能仍然拥有 withStyles HOC 但包含 innerRef 和其他道具?
从材料 ui v3 迁移到 v4 后出现此问题。NavLink 需要 innerRef 属性。
解决方案
withStyles
将 innerRef 作为 ref 传递,所以类似下面的东西应该可以工作:
const MyComponent = withStyles(styles)(({ one, two, ...props }, ref) => {
return (
<Fragment>
<NavLink {...props} ref={ref}></NavLink>
...
</Fragment>
);
})
或者,如果您需要将其保持为innerRef
on NavLink
:
const MyComponent = withStyles(styles)(({ one, two, ...props }, ref) => {
return (
<Fragment>
<NavLink {...props} innerRef={ref}></NavLink>
...
</Fragment>
);
})
推荐阅读
- reactjs - Trying to do on React a List whos every item log on screen every second. Wrote a code, but gives an error (
- html - 如何保持 HTML 输入标签值
- android - 在 Flutter 中使用本机代码获取前台位置,无需任何 pub 包
- debugging - 我想安装 streamlit,但由于 pyarrow 依赖项而出现此错误
- python - 将 python 字符串转换为逗号分隔的双引号列表
- c++ - 根据某些功能,将双精度数组有效(按时间)转换为位集
- amazon-managed-blockchain - 我可以使用 t2.micro 运行 AWS 以太坊预览版吗
- vba - 有没有办法在打开文件时包含两个文件扩展名
- ruby - 输入意外结束?
- python - 有什么方法可以将摩根指纹转换为我可以弄清楚它是什么分子的方式?