首页 > 解决方案 > reactjs 切换自定义主题无法按预期工作

问题描述

我有三个基本的自定义主题,我想在它们之间切换。

我有一些问题/疑问:

  1. 为什么来自 CustomToolbar.jsx 的容器正在“工作”,而来自 Component1.jsx 的容器却没有?
  2. 为什么 App.js 中的按钮正在改变背景而组件中的按钮没有?(也应该)
  3. 有时,当我多次单击 CustomToolbar 中的按钮时,出现错误:
Warning: Failed prop type: The prop `theme` is marked as required in `ThemeProvider`, but its value is `undefined`.
    in ThemeProvider (at CustomThemeProvider.js:37)

    in CustomThemeProvider (at src/index.js:11) 

我不知道如何管理它们,任何如何改进代码的帮助都会很棒。

https://codesandbox.io/s/musing-cache-s92ez

标签: reactjsmaterial-uithemes

解决方案


问题 1 和 2:这是因为您将每个组件都包装在ThemeProvider/MuiThemeProvider中,这样做会覆盖您的自定义主题。

App将你的内部包裹CustomThemeProvider在你的 index.js 上就足够了。


问题3:单击时e.target.innerHTML不会总是返回按钮内的文本。尝试控制台记录,然后单击按钮而不是文本,您会看到类似

<span class="MuiButton-label">red</span><span class="MuiTouchRipple-root"><span class="MuiTouchRipple-ripple MuiTouchRipple-rippleVisible" style="width: 128.825px; height: 128.825px; top: -35.4127px; left: -8.41273px;"><span class="MuiTouchRipple-child MuiTouchRipple-childLeaving"></span></span></span> 

要解决此问题,您可以e.currentTarget.textContent改用。

请查看下面的演示。

编辑busy-saha-8rjrc


推荐阅读