【问题标题】:How to pass props of React component to styled component如何将 React 组件的 props 传递给样式化组件
【发布时间】:2019-06-26 20:22:34
【问题描述】:

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

我尝试了以下方法:

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

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

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

【问题讨论】:

    标签: reactjs styled-components


    【解决方案1】:

    你的语法很好用。我怀疑问题出在height 的值上。我怀疑它不起作用,因为您指定的是像 200 这样的整数,而不是像 200px 这样的有效 CSS 高度字符串。

    下面是一个简单的例子:

    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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-17
      • 2015-07-12
      • 1970-01-01
      • 2017-09-14
      • 2020-10-28
      • 1970-01-01
      • 2016-12-24
      • 1970-01-01
      相关资源
      最近更新 更多