下面我创建了一个名为 Link 的样式。然而,主题在 this.props
中。从 Prop 中获取主题并传递到 Link
样式组件中的方法是什么?
ReferenceError: theme is not defined
import React from 'react';
import styled from 'styled-components';
import { withTheme } from 'styled-components';
export const Link = styled.p`
position: absolute;
z-index: 10;
bottom: 20px;
right: 300px;
width: 100%;
font-size: 1.5rem;
text-align: right;
cursor: pointer;
a {
color: ${theme.apricot}; // <-- error
cursor: pointer;
:hover {
color: ${theme.offWhite}; // <-- error
}
}
`;
class NomicsLink extends React.Component {
render() {
console.log(this.props.theme);
return (<Link>Powered by <a href="https://nomics.com/" target="blank">Nomics APIs.</a></Link>)
}
}
export default withTheme(NomicsLink);
此 console.log 打印以下内容:
{ red: '#FF0000',
black: '#393939',
grey: '#3A3A3A',
lightgrey: '#E1E1E1',
offWhite: '#EDEDED',
apricot: '#FEBE7E',
margin: 0,
padding: 0 }
最佳答案
所有 styled-components
自动接收 theme
属性。
您可以在带样式的组件中访问它们:
const Link = styled.a`
color: ${props=>props.theme.apricot};
`;
有关主题的更多选项,请参阅 docs
关于javascript - 如何在组件内部使用 StyledComponents 主题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54314554/