首页 > 解决方案 > 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 属性。

标签: javascriptreactjsmaterial-uihigher-order-componentsreact-with-styles

解决方案


withStyles 将 innerRef 作为 ref 传递,所以类似下面的东西应该可以工作:

const MyComponent = withStyles(styles)(({ one, two, ...props }, ref) => {
    return (
        <Fragment>
            <NavLink {...props} ref={ref}></NavLink>
              ...
        </Fragment>
    );
})

或者,如果您需要将其保持为innerRefon NavLink

const MyComponent = withStyles(styles)(({ one, two, ...props }, ref) => {
    return (
        <Fragment>
            <NavLink {...props} innerRef={ref}></NavLink>
              ...
        </Fragment>
    );
})

推荐阅读