如果您将Checkbox 包装在div 中,Tooltip 将正常工作,如下所示:
<Tooltip title="This tooltip works great">
<div>
<Checkbox label="This tooltip works on both text and checkbox." />
</div>
</Tooltip>
<Tooltip title="This tooltip does not work">
<Checkbox label="This tooltip does not work hovering on text, only hovering on checkbox." />
</Tooltip>
原因
Tooltip 组件通过响应其子组件(onMouseEnter、onMouseLeave 和其他几个)上的事件来工作。它通过将 props 应用于顶级子级来注册这些事件。
当您将 Checkbox 包装在 div 中时,div 会收到 onMouseEnter 和 onMouseLeave 道具,因此悬停可以正常工作。
但是,当您没有包装 div 时,您的自定义 Checkbox 将接收 onMouseOver 和 onMouseLeave 作为其 props 的一部分。你把这些props 传播到MuiCheckbox 中,如下所示:
<FormControlLabel
control={<MuiCheckbox {...props} />}
label={label ? label : ""}
/>
因此,您实际上仅将onMouseOver 和onMouseLeave 应用于MUICheckbox 本身,而不是应用于标签。所以悬停只适用于Checkbox 而不是标签。
如果你愿意,你也可以通过在整个自定义组件中传播 props 来解决这个问题:
export const Checkbox = ({ error, helperText, ...props }) => {
// Capture all of the other props in other
let { disabled, label, ...other } = props;
let icon;
if (disabled) icon = <Info color="disabled" />;
else if (error) icon = <Warning color="error" />;
// Spread the other props throughout the top-level div
return (
<div {...other}>
<div>
<FormControlLabel
control={<MuiCheckbox {...props} />}
label={label ? label : ""}
/>
{!!helperText && (
<FormHelperText error={error} disabled={disabled}>
{!!icon && icon}
{helperText}
</FormHelperText>
)}
</div>
</div>
);
};
我最初没有建议该解决方案,因为如果您不小心,它可能会更改组件的逻辑,而包装 div 应该非常安全。