简体   繁体   English

无法将 styles 应用于 Reactjs 中的样式化组件元素

[英]Unable to apply styles to styled-component element in Reactjs

I'm trying to wrap a component with a styled-component div and apply some styles.我正在尝试使用styled-component div 包装组件并应用一些 styles。 However, for some reason, the styles aren't being applied, even though the ostensibly correct wrapper that is expected to be rendered is being rendred.但是,由于某种原因,styles 没有被应用,即使正在渲染预期要呈现的表面上正确的包装器。

CodeSandbox 代码沙盒

What am I doing wrong here?我在这里做错了什么?

You just forgot to pass the className props, see here:您只是忘记传递 className 道具,请参见此处:

const Component = ({ className }) => (
  <div className={className}>Hello World!</div>
);

https://codesandbox.io/s/optimistic-lumiere-cq8gt?file=/src/App.js https://codesandbox.io/s/optimistic-lumiere-cq8gt?file=/src/App.js

I hope I helped you.我希望我对你有所帮助。 Have a good day.祝你有美好的一天。

EDIT:Check the docs here编辑:在这里查看文档

You need to container Component with styled.{tag} or styled(Component) And then use that Container component to wrap main component.您需要使用styled.{tag}styled(Component)容器组件,然后使用该容器组件包装主要组件。

import React from "react";
import "./styles.css";
import styled from "styled-components";

export default () => <Component />;

const Component = () => <StyledDiv>Hello World!</StyledDiv>;

const StyledDiv = styled.div`
  font-size: 10rem;
  color: red;
  display: flex;
  justify-content: center;
  align-items: center;
`;

Check here: https://codesandbox.io/s/dank-hill-h8rbc?file=/src/App.js:128-189在这里查看: https://codesandbox.io/s/dank-hill-h8rbc?file=/src/App.js:128-189

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM