MUI下一个工具提示在悬停时不显示

时间:2018-02-22 14:49:00

标签: javascript reactjs ecmascript-6 material-ui

我使用带有Checkbox和FormControlLabel的Material-UIv1.0.0-beta.34工具提示,实际上当我在一个案例中将鼠标悬停在Checkbox上的标签时,当我创建一个新组件时,工具提示在另一只手上按预期显示(自定义)使用FormControlLabel和Checkbox,看起来工具提示无法按预期工作。

https://codesandbox.io/s/n33p76n28p

1 个答案:

答案 0 :(得分:2)

如果您将Tooltip包裹在Checkbox中,div将正常运行:

<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组件通过响应其子组件(onMouseEnteronMouseLeave和其他几个组件上的事件来工作。它通过将道具应用于顶级孩子来注册这些事件。

当您将Checkbox打包到div时,div会收到onMouseEnteronMouseLeave道具,因此悬停可以正常使用。

但是,当您没有换行div时,您的自定义Checkbox会收到onMouseOveronMouseLeave作为其props的一部分。您可以使用这些props并将其展开到MuiCheckbox中,如此:

<FormControlLabel
  control={<MuiCheckbox {...props} />}
  label={label ? label : ""}
/>

因此,您有效地仅将onMouseOveronMouseLeave应用于MUICheckbox本身,而不是标签。因此,悬停仅适用于Checkbox,而不适用于标签。

如果您愿意,还可以通过在整个自定义组件中传播道具来解决此问题:

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应该是非常安全的。