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

oez*_*nsi 1 reactjs styled-components

我正在尝试基于props它所在的React组件的设置样式组件的高度。

我尝试了以下方法:

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

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

但是不知何故,它不起作用。有人可以帮我吗?我要尝试的最佳做法是什么?

Rya*_*ell 5

您使用的语法效果很好。我怀疑问题在于的价值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);
Run Code Online (Sandbox Code Playgroud)

编辑945v7xjw1w