我正在尝试像这样使用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”
答案 0 :(得分:4)
您需要使用一个回调,该回调接受像这样传递给组件的props
:
const MyStyledComponent = styled.div`
position: fixed;
top: ${(props) => props.top};
`;
<MyStyledComponent top={5} />;
奖金:通常在使用css-in-js时
(例如styled-component
)和many handy tools等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" />
</>
);
};