简体   繁体   中英

How to pass props of React component to styled component

I am trying set the height of a styled component based on the props of the React component it is in.

I tried the following:

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

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

But somehow it doesn't work. Can somebody help me out? What is the best practice for what I am trying to do?

The syntax you have works just fine. I suspect the problem is the value of height . I suspect it isn't working because you are specifying an integer like 200 rather than a valid CSS height string like 200px .

Here's a simple example that works:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM