简体   繁体   English

如何在 React 风格的组件中使用 this.props

[英]How to use this.props in React Styled Components

I am trying to style my component using props likes this:我正在尝试使用像这样的props来设计我的组件:

const MyStyledComponent = styled.div`
    position: fixed;
    top: ${this.props.style.top};
    left: ${this.props.style.left};
    width: ${this.props.style.width};
    height: ${this.props.style.height};
`;

But I am getting the following error:但我收到以下错误:

Uncaught TypeError: Cannot read property 'props' of undefined未捕获的类型错误:无法读取未定义的属性“props”

You need to use a callback which accepts props passed to the component like so:您需要使用一个回调来接受传递给组件的props ,如下所示:

const MyStyledComponent = styled.div`
  position: fixed;
  top: ${(props) => props.top};
`;

<MyStyledComponent top={5} />;

See Getting Started in docs .请参阅文档中的入门


Bonus: typically when working with css-in-js (like styled-component ), there are many handy tools that used alongside, like styled-tools .奖励:通常在使用 css-in-js(如styled-component )时,有许多方便的工具可以一起使用,如styled-tools

import styled, { createGlobalStyle } from "styled-components";
import { prop } from "styled-tools";

const GlobalStyle = createGlobalStyle`
  body {
    margin: 0;
    padding: 5px;
    border: 5px solid pink;
  }
`;

const Box = styled.div`
  height: ${({ height }) => height}px;
  width: ${({ width }) => width}px;
  background-color: ${({ color }) => color};
`;

const Box2 = styled.div`
  ${({ height, width, color }) => ({
    height,
    width,
    "background-color": color
  })}
`;

const Box3 = styled.div`
  height: ${prop("height")}px;
  width: ${prop("width")}px;
  background-color: ${prop("color")};
`;

const N = 100;

const App = () => {
  return (
    <>
      <GlobalStyle />
      <Box width={N} height={N} color="palevioletred" />
      <Box2 width={N * 1.5} height={N * 1.5} color="black" />
      <Box3 width={N * 2} height={N * 2} color="palegoldenrod" />
    </>
  );
};

编辑深情-月亮-netoi

在此处输入图像描述

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

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