React Forwardref 不能像自定义组件那样工作
React Forward Ref not working as with Custom Compoent
我需要将自定义组件包装在 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>);
这里是沙盒linkhttps://codesandbox.io/s/material-ui-card-styling-example-forked-9tqod?file=/src/index.js:438-914
首先你需要更新所有版本,尤其是MUI版本。
其次,您还需要传递 props,以便将 Tooltip 样式和事件应用到内部组件。
Everything mentioned in 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
我需要将自定义组件包装在 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>);
这里是沙盒linkhttps://codesandbox.io/s/material-ui-card-styling-example-forked-9tqod?file=/src/index.js:438-914
首先你需要更新所有版本,尤其是MUI版本。
其次,您还需要传递 props,以便将 Tooltip 样式和事件应用到内部组件。
Everything mentioned in 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