【问题标题】:MUI next Tooltip does not show on hover悬停时不显示 MUI 下一个工具提示
【发布时间】:2018-02-22 14:49:00
【问题描述】:

我将 Material-UIv1.0.0-beta.34 Tooltip 与 Checkbox 和 FormControlLabel 一起使用,实际上,当我将鼠标悬停在 Checkbox 上的标签上时,另一方面,当我创建一个新的组件(自定义)时,工具提示会按预期显示里面有 FormControlLabel 和 Checkbox,它看起来工具提示没有按预期工作。

https://codesandbox.io/s/n33p76n28p

【问题讨论】:

    标签: javascript reactjs ecmascript-6 material-ui


    【解决方案1】:

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

    当您将 Checkbox 包装在 div 中时,div 会收到 onMouseEnteronMouseLeave 道具,因此悬停可以正常工作。

    但是,当您没有包装 div 时,您的自定义 Checkbox 将接收 onMouseOveronMouseLeave 作为其 props 的一部分。你把这些props 传播到MuiCheckbox 中,如下所示:

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

    因此,您实际上仅将onMouseOveronMouseLeave 应用于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 应该非常安全。

    【讨论】:

    • @PalaniichukDmytro 我已经扩展了我的答案以解释为什么包装 div 可以解决您的问题。
    • 非常感谢,现在更清楚的是 tooltip 将其道具填充到孩子们
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-20
    • 1970-01-01
    相关资源
    最近更新 更多