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

问题描述

我将使用React.forwardRef的引用传递到通常可用的down组件。

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

但是,当我将HOC(高阶组件)与Styles一起使用时,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,...props }) => {
    return (
        <Fragment>
            <NavLink {...props}></NavLink>
              ...
        </Fragment>
    );
}

我如何仍然可以使用withStyles HOC,但要包含innerRef和其他道具?

从材料ui v3迁移到v4后出现此问题。 NavLink需要innerRef属性

解决方法

withStyles passes along innerRef as ref,因此应执行以下操作:

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

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

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

基于我的评论的建议:

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

或者

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...