我将使用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, two, ...props }) => {
return (
<Fragment>
<NavLink {...props}></NavLink>
...
</Fragment>
);
}
我如何仍然可以使用withStyles HOC,但要包含innerRef和其他道具?
从材料ui v3迁移到v4后出现此问题。 NavLink需要innerRef属性。
答案 0 :(得分:1)
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, two, ...props }, ref) => {
return (
<Fragment>
<NavLink {...props} innerRef={ref}></NavLink>
...
</Fragment>
);
})
答案 1 :(得分:0)
基于我的评论的建议:
<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>