如何将 React 组件的 props 传递给样式化组件

IT技术 reactjs styled-components
2021-05-16 18:43:45

我正在尝试根据props它所在的 React 组件的高度设置样式组件的高度

我尝试了以下方法:

const Styled = styled.div`
    height: ${props => props.height}
`

class Parent extends React.Component {
  render() {
      return (
          <Styled height={this.props.height}/>
      )
  }
}

但不知何故它不起作用。有人可以帮我吗?我正在尝试做的最佳实践是什么?

1个回答

你的语法工作得很好。我怀疑问题是height. 我怀疑它不起作用,因为您指定的是一个整数,200而不是一个有效的 CSS 高度字符串,例如200px.

这是一个有效的简单示例:

import React from "react";
import ReactDOM from "react-dom";
import styled from "styled-components";

const Styled = styled.div`
  height: ${props => props.height};
  background-color: blue;
  color: white;
`;

function App() {
  return (
    <Styled className="App" height="200px">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </Styled>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

编辑 945v7xjw1w