withSyles HOC 在通过 React.forwardRef 时不会将 innerRef 与其他道具一起传递

withSyles HOC does not pass innerRef along with other props when passing through React.forwardRef

我正在使用 React.forwardRef 将 ref 传递给通常有效的向下组件。

<SomeComponent
component={React.forwardRef((props, ref) => <MyComponent innerRef={ref} {...props} />)}
.../>

然而,当我有 HOC(高阶组件)withStyles 时,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>
    );
}

如何在包含 innerRef 和其他道具的情况下仍然拥有 withStyles HOC?

从 material ui v3 迁移到 v4 后出现此问题。 NavLink requires innerRef 属性.

根据我的评论我的推荐:

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

或者

<NavLink {...props} innerRef={props.nRef}></NavLink>

withStyles passes along innerRef as ref,所以像下面这样的东西应该可以工作:

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

或者,如果您需要在 NavLink 上将其保留为 innerRef

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