【问题标题】:is there an easy way to use theme colors in react-autosuggest items有没有一种简单的方法可以在 react-autosuggest 项目中使用主题颜色
【发布时间】:2019-03-19 22:33:56
【问题描述】:

我正在尝试使用 react-autosuggest,因为它被设计为,对我来说,renderSuggestion 的方法签名应该包含实际的主题,所以我们可以在我们的主题中使用来自主题的变量造型

这是我的解决方法,但我只是想确保我没有做一些无用的复杂操作:

                                        <AutoSuggest
                                                renderSuggestion={createRenderSuggestion(this.props.classes)}
/>

变量 this.props.classes 在组件创建时填充

withStyles(styles)(ShopSuggestBox)

我必须在方法中定义一个方法才能访问实际的主题

const createRenderSuggestion = theme => suggestion => {
    console.log("setting css of name:", theme.itemName)
    return (
            <div>
                <div className={theme.itemName}>
                    {suggestion.name}
                </div>
                <div className={theme.itemInfo}>
                    NYC
                </div>
            </div>
    )
}

只是为了确保清楚:当我尝试在 function renderSuggestion(suggestion, { query, isHighlighted }) 方法中访问主题时,我不能

【问题讨论】:

  • @moroshko 我没有找到 react-autosuggest 的标签

标签: material-ui autosuggest


【解决方案1】:

看看https://material-ui.com/customization/themes/#accessing-the-theme-in-a-component

如果您不想作曲,也可以使用withStyles(styles, { withTheme: true })(ShopSuggestBox);

无论哪种方式,theme 都可以在 ShopSuggestBox 的道具中访问。

【讨论】:

  • 嗨@epsilon,感谢您的回答。确实,现在我添加了 withStyles(styles, { withTheme: true }),主题在道具中变得可用。问题是它没有包含我作为参数传递给 withStyles 的新样式。是不是只覆盖了现有的样式???
  • withStyles(styles) 中的样式在props.classes 中可用。请记住,这些只是类名而不是实际的样式对象。如果您需要内联样式,则不必使用 withStyles
  • ps:在你指出我的文档中,有关于 withTheme 的信息,我查看了 withStyles 的文档,我没有看到 {withTheme: true } 选项:material-ui.com/guides/typescript/#usage-of-withstyles 我认为是令人困惑的文档作为新材料,因为存在描述的问题但没有推荐的最佳实践
  • 感谢它在使用 props.classes 时起作用,我找到了我的属性。对我来说不幸的是,仍然不清楚为什么不将这些属性插入到样式对象中(是为了避免样式在整个应用程序上传播吗?):在我天真的想法中,我想象样式对象用重写的值和由于 withStyles 调用而添加了属性。我知道我错了,但为什么呢?
  • @ZiedHamdi 我认为每个问题都在material-ui.com/customization/css-in-js 中回答,您链接的部分特定于打字稿。它并不意味着作为 withStyles 的完整文档
猜你喜欢
  • 1970-01-01
  • 2010-12-22
  • 2010-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-30
相关资源
最近更新 更多