【问题标题】:Calculate height of styled-components计算样式组件的高度
【发布时间】:2019-09-02 11:38:02
【问题描述】:

对于样式组件,我如何获取任何特定 div 的高度? 例如,在下面的例子中,我怎样才能得到 Outer 标签的高度(100px),

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

import "./styles.css";

function App() {
  const Outer = styled.div`
    height: "100px";
    border: 1px solid black;
  `;
  return (
    <div className="App">
      <Outer>Inside</Outer>
    </div>
  );
}

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

我尝试过Outer.height(),但它不起作用。如何获取 Outer 标签的高度?

【问题讨论】:

  • 如果您真的想获得通过样式化组件输入的值,您可以查看库构建的样式表并对其进行解析。我已经根据您的另一个答案改编了我的代码。 codesandbox.io/s/1y5rmvxlkl - 然而这(通常)是矫枉过正的。 Deve 的回答可能就足够了。

标签: javascript html css reactjs styled-components


【解决方案1】:

你可以声明外层标签并在标签上使用。

function App() {
  const heightApp: 100
  const Outer = styled.div`
    height: "`${heightApp}`px";
    border: 1px solid black;
  `;
  return (
    <div className="App">
      <Outer>Inside</Outer>
    </div>
  );
}

【讨论】:

    【解决方案2】:

    您可以添加参考以获取Outer 的大小并执行this.outerRef.current.clientHeight

    类似的东西:

    const Outer = styled.div`
      height: 100px;
      background: red;
    `;
    
    export default class App extends React.Component {
      constructor(props) {
        super(props);
        this.outerRef = React.createRef();
        this.state = {
          outerHeight: 0
        };
      }
    
      componentDidMount() {
        this.setState({ outerHeight: this.outerRef.current.clientHeight });
      }
    
      render() {
        return (
            <Container ref={this.outerRef}>
              {this.state.outerHeight}
            </Container>
        );
      }
    }
    
    

    您可以查看:https://codesandbox.io/embed/6yq239ljlk?fontsize=14

    这行得通,但我不知道它是否需要高度。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-19
      • 1970-01-01
      • 2018-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-07
      • 1970-01-01
      相关资源
      最近更新 更多