简体   繁体   English

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

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

I'm passing the ref using React.forwardRef to the down component which usually works.我正在使用React.forwardRef将 ref React.forwardRef给通常有效的向下组件。

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

However when I have HOC (higher order component) withStyles, the innerRef along with other props do not get passed properly.然而,当我有 HOC(高阶组件)withStyles 时,innerRef 和其他 props 没有被正确传递。

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

Without using withStyles I get them perfectly不使用 withStyles 我就能完美地得到它们

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

How can I still have the withStyles HOC but with innerRef and other props included?我如何仍然拥有 withStyles HOC 但包含 innerRef 和其他道具?

The issue appeared after migration from material ui v3 to v4.从材料 ui v3 迁移到 v4 后出现该问题。 NavLink requires the innerRef property. NavLink 需要 innerRef 属性。

withStyles passes along innerRef as ref , so something like the following should work: withStyles 将 innerRef 作为 ref 传递,因此应该可以使用以下内容:

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

Or if you need to keep it as innerRef on NavLink :或者,如果您需要将其保留为innerRef上的NavLink

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

My recommendation based on my comments:我的建议基于我的评论:

<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>
    );
})

Or alternatively或者替代地

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM