对于样式组件,我如何获取任何特定 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()
但它不起作用。如何获取外部标签的高度?
最佳答案
您可以添加引用以获取 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
这行得通,但我不知道在这条路上是否需要高度。
关于javascript - 计算样式组件的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55639191/