如何在React样式组件中使用this.props

时间:2020-06-11 13:08:26

标签: javascript reactjs styled-components

我正在尝试像这样使用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};
`;

但是我遇到以下错误:

未捕获的TypeError:无法读取未定义的属性“ props”

1 个答案:

答案 0 :(得分:4)

您需要使用一个回调,该回调接受像这样传递给组件的props

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

<MyStyledComponent top={5} />;

请参见Getting Started in docs


奖金:通常在使用css-in-js时 (例如styled-component)和many handy toolsstyled-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" />
    </>
  );
};

Edit affectionate-moon-netoi

enter image description here