import React from "react";
interface IXWindowWidth {
children(w: number): React.ReactElement<HTMLDivElement>;
}
interface IState {
w: number;
}
export class XWindowWidth extends React.Component<IXWindowWidth, IState> {
state: IState = {
w: window.innerWidth
};
onResize = () => {
this.setState({ w: window.innerWidth });
};
componentDidMount() {
window.addEventListener("resize", this.onResize);
}
componentWillUnmount() {
window.removeEventListener("resize", this.onResize);
}
render() {
return <div>{this.props.children(this.state.w)}</div>;
}
}
使用
import { XWindowWidth } from "./windowWidth";
export default function App() {
return (
<div className="App">
<XWindowWidth>
{
w => <div>window的宽度为: {w}</div>
}
</XWindowWidth>
</div>
);
}