reactjs - 对于带有 React Router 的样式化组件,子组件没有 props.theme
问题描述
import {theme} from "./themes";
const App = () => (
<ThemeProvider theme={theme}>
<ErrorBoundary showError>
<Provider store={store}>
<Router>
<switch>
<Route path="/page1" exact component={Page} />
<Route path="/notfound" component={NotFound} />
</switch>
</Router>
</Provider>
</ErrorBoundary>
</ThemeProvider>
export default hot(module)(App);
现在在我的页面组件中,我的道具不包括主题,即 props.theme 未定义
有人可以告诉我哪里出错了吗?
我的页面组件有减速器、位置、匹配道具但没有主题
解决方案
正如文档中所写:
在渲染树中,所有样式组件都可以访问提供的主题
只有他们!
这意味着您的“普通”组件不会在其道具中获取主题对象。我花了一些时间才明白。他们本可以在文档中写得更好一些。
Themeprovider 使用react-context api,这意味着您放入其中的所有内容都将在 this.context.yourVaribaleName 下可用,而不是在道具中,这是两个不同的东西。 (有关进一步和正确的用法,请参阅上下文 api 的官方反应文档(上一个链接))
因此,您只需在页面组件中执行以下操作:
const Button = styled.button`
font-size: 1em;
color: ${props => props.theme.main};
border: 2px solid ${props => props.theme.main};
`;
class Page extends React.Component {
render(){
return(<Button>Normal</Button>);
}
}
(styled 组件中的 props.theme 并不意味着您将在其中使用 styled-component 的组件,它的 props 中也有这个)
或者
如果您希望主题对象位于样式组件之外,则在“普通”组件道具中,您必须使用 withTheme HOC。请参阅文档。(如前一个答案中所述)
推荐阅读
- ios - 无法从 CLGeocoder() 保存经度和纬度
- c - 我怎样才能只得到一个数字作为主函数的参数?
- html - dfSummary - Rmarkdown 中 html 输出中的格式化因子级别?
- reporting-services - SSRS 订阅使用缓存数据
- php - 为什么 Mpdf 不起作用并且没有返回错误
- r - 无法使用子 .Rmd 中的图像编译 RMarkdown pdf - LaTeX 错误 - 找不到图像文件
- vue.js - NativeScript Vue.js 添加链接到网站的按钮
- arrays - 在二维数组中生成/放置 k 个随机项
- pandas - 如果一列中的单元格位于其他 4 列中的任意一列,则创建一列来回答
- c# - 用于 c# 作业的弹性 apm