【问题标题】:MaterialUI -withStyles hoc causes <Select /> menu to close when it shouldn'tMaterial UI -withStyles hoc 导致 <Select /> 菜单在不应该关闭时关闭
【发布时间】:2021-01-04 11:52:16
【问题描述】:

当前行为

&lt;Select /&gt; 组件与multiple 一起使用时,用户应该能够在不关闭菜单的情况下选择多个选项。这在实例化 &lt;Select /&gt; 组件时按预期工作,但在将它与 withStyles() HOC 一起使用时,它会自动关闭。

演示:

https://user-images.githubusercontent.com/8508891/93466086-fb93ec80-f8eb-11ea-8f81-89443085eabe.gif

// Here we use the HOC and this is where it breaks.
const NewSelect = (props) => {
  const StyledSelect = withStyles({
    // styles etc
}, { name: "NewSelect" })(Select);

  return <StyledSelect {...props} />;
};

// Closes when item selected
<NewSelect multiple { ... } />

// Doesn't close (desired behavior)
<Select multiple { ... } />

预期行为????

当使用withStyles() HOC 时,包装后的 Select 的行为应该相同。

复制步骤????

查看示例: https://codesandbox.io/s/material-demo-forked-38rhd?file=/demo.js

上下文????

我们的设计系统在后台使用了一些 MUI 组件;因此,为了连接到我们的主题,我们使用 withStyles() 来包装 Mui 组件并应用我们主题中的特定样式。

环境????

|技术 |版本 | | ------------ | -------- | |材质-UI | v5.0.0-alpha | |反应 | 16.13.1 |

【问题讨论】:

    标签: javascript reactjs material-ui


    【解决方案1】:

    您应该将StyledSelect 声明移到Select2 之外,因为每次输入更改都会导致Select2 被重新渲染(我在其中放了一个console.log 以便您清楚地看到),再次声明StyledSelect,这导致你的意外行为

    解决方案

    const StyledSelect = withStyles({})(Select);
    
    const Select2 = (props) => {
      console.log("rerender");
      // If we chance StyledSelect to Select (Mui one), it works fine.
      return <StyledSelect {...props}>{props.children}</StyledSelect>;
    };
    

    演示

    【讨论】:

    • 谢谢!我还需要将道具传递给 withStyles 中第一个参数的对象。试图把它变成一个箭头函数,但我得到“对象作为 React 孩子无效”。:(
    • @LucasArundell 很酷,我以前从未注意到过这种情况,TIL
    猜你喜欢
    • 2020-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-10
    • 1970-01-01
    • 2017-05-18
    • 2020-01-30
    • 2020-04-07
    相关资源
    最近更新 更多