计算样式化组件的高度

时间:2019-04-11 18:39:33

标签: javascript html css reactjs styled-components

对于样式化组件,我如何获取任何特定div的高度? 例如,在下面的示例中,如何获取外部代码的高度(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(),但是它不起作用。如何获得外部标签的高度?

2 个答案:

答案 0 :(得分:1)

您可以添加引用以获取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

这有效,但我不知道它是否需要这种高度。

答案 1 :(得分:-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>
  );
}
相关问题