样式组件未将样式应用于自定义功能反应组件

styled-components not applying style to custom functional react component

当使用 styled-components 设置自定义功能性 React 组件的样式时,未应用样式。这是 simple example,其中样式未应用于 StyledDiv:

const Div = () => (<div>test</div>)
const StyledDiv = styled(Div)`
  color: red;
`;

确保正确应用样式的最佳方法是什么?

来自docs

The styled method works perfectly on all of your own or any third-party components as well, as long as they pass the className prop to their rendered sub-components, which should pass it too, and so on. Ultimately, the className must be passed down the line to an actual DOM node for the styling to take any effect.

例如,您的组件将变为:

const Div = ({ className }) => (<div className={className}>test</div>)
const StyledDiv = styled(Div)`
  color: green;
`;

修改示例:

const styled = styled.default
const Div = ({ className }) => (<div className={className}>test</div>)
const StyledDiv = styled(Div)`
  color: green;
  font-size: larger;
`;
const App = () => {
  return(<StyledDiv>Test</StyledDiv>)
}

ReactDOM.render(<App />, document.querySelector('.app'))
<script src="//unpkg.com/react@16.5.2/umd/react.development.js"></script>
<script src="//unpkg.com/react-dom@16.5.2/umd/react-dom.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/styled-components/3.4.9/styled-components.min.js"></script>
<div class="app"></div>

像这样使用 styled(Component) 创建一个 class,它作为一个名为 className 的 prop 传递给包装的组件。

然后您可以将其应用于根元素:

const Div = ({ className }) => (
  <div className={className}>test</div>
)

const StyledDiv = styled(Div)`
  color: red;
`;

如果您无法更改原始组件(它是导入的或生成的),我们假设该组件是 <span>,您可以用例如a <div> 并嵌套 css 规则,如下所示:

const ComponentICantTouchWrapper = ({className}) => (
    <div className={className}><ComponentICantTouch /></div>
);
const StyledComponentICantTouch = styled(ComponentICantTouchWrapper)`
    > span {
        color: red;
    }
`;

在我的例子中,我试图将带样式的组件与 material UI 一起使用。我的想法是这样做:(在大多数情况下都有效)

const StyledTableRow = ({ className, children }) => (
    <TableRow className={className}>{children}</TableRow>
);