计算样式组件的高度
Calculate height of 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()
,但没用。如何获取外标签的高度?
您可以声明外部标签并在标签上使用。
function App() {
const heightApp: 100
const Outer = styled.div`
height: "`${heightApp}`px";
border: 1px solid black;
`;
return (
<div className="App">
<Outer>Inside</Outer>
</div>
);
}
您可以添加引用以获取 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
这可行,但我不知道您是否需要高度。
对于样式化组件,如何获取任何特定 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()
,但没用。如何获取外标签的高度?
您可以声明外部标签并在标签上使用。
function App() {
const heightApp: 100
const Outer = styled.div`
height: "`${heightApp}`px";
border: 1px solid black;
`;
return (
<div className="App">
<Outer>Inside</Outer>
</div>
);
}
您可以添加引用以获取 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
这可行,但我不知道您是否需要高度。