最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to use this.props in React Styled Components - Stack Overflow

programmeradmin1浏览0评论

I am trying to style my ponent using props likes this:

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

I am trying to style my ponent using props likes this:

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

Share Improve this question asked Jun 11, 2020 at 13:08 FunnelScrFunnelScr 1711 silver badge15 bronze badges 1
  • You should use destructuring to get nested object values, you can use fallback values in case props aren't available. – Joost Meijer Commented Jun 17, 2021 at 7:44
Add a ment  | 

1 Answer 1

Reset to default 12

You need to use a callback which accepts props passed to the ponent like so:

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-ponent), there are many handy tools that used alongside, like styled-tools.

import styled, { createGlobalStyle } from "styled-ponents";
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" />
    </>
  );
};

发布评论

评论列表(0)

  1. 暂无评论