如何解决React Forward Ref 与自定义组件不同
我需要在 Material UI 工具提示中包装我的自定义组件。我相信我正确地使用了 ForwardRefs,但是无论事件(悬停、点击等)如何,工具提示都不会出现
const MyComp = ({ buttonRef }) => {
return <button ref={buttonRef}>this does not work</button>;
};
const MyCompForwardRef = React.forwardRef((props,ref) => {
return <MyComp {...props} buttonRef={ref} />;
});
const FancyButton = React.forwardRef((props,ref) => (
<button ref={ref}>this also does not work</button>
));
const Page = () => (
<div style={{ display: "flex",flexDirection: "column" }}>
<div style={{ margin: "10px" }}>
<Tooltip title="23456789">
//not working
<MyCompForwardRef />
</Tooltip>
</div>
<div style={{ margin: "10px" }}>
<Tooltip title="23456789">
//not working
<FancyButton />
</Tooltip>
</div>
<div style={{ margin: "10px" }}>
<Tooltip title="23456789">
<button>this works</button>
</Tooltip>
</div>
</div>);
这是沙盒链接https://codesandbox.io/s/material-ui-card-styling-example-forked-9tqod?file=/src/index.js:438-914
解决方法
首先需要更新所有版本,尤其是MUI版本。
其次,你也需要传递 props,所以它会将 Tooltip 样式和事件应用到内部组件。
MUI docs 中提到的所有内容
const MyComp = ({ buttonRef,...props }) => {
return (
<button {...props} ref={buttonRef}>
work
</button>
);
};
const MyCompForwardRef = React.forwardRef((props,ref) => {
return <MyComp {...props} buttonRef={ref} />;
});
const FancyButton = React.forwardRef((props,ref) => {
return (
<button {...props} ref={ref}>
work
</button>
);
});
https://codesandbox.io/s/mui-forwardref-tooltip-issue-forked-8u5vm?file=/src/index.js
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。