发表更新1 分钟读完 (大约206个字)
react-hooks的优势
逻辑复用
使用传统的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| const withWindowSize = Component => { class WrappedComponent extends React.PureComponent { constructor(props) { super(props); this.state = { size: this.getSize() }; } componentDidMount() { window.addEventListener("resize", this.handleResize); } componentWillUnmount() { window.removeEventListener("resize", this.handleResize); } getSize() { return window.innerWidth > 1000 ? "large" : "small"; } handleResize = () => { const currentSize = this.getSize(); this.setState({ size: this.getSize() }); } render() { return <Component size={this.state.size} />; } } return WrappedComponent; };
class MyComponent extends React.Component { render() { const { size } = this.props; if (size === "small") return <SmallComponent />; else return <LargeComponent />; } }
export default withWindowSize(MyComponent);
|
使用hooks
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| const getSize = () => { return window.innerWidth > 1000 ? "large" : "small"; } const useWindowSize = () => { const [size, setSize] = useState(getSize()); useEffect(() => { const handler = () => { setSize(getSize()) }; window.addEventListener('resize', handler); return () => { window.removeEventListener('resize', handler); }; }, []); return size; };
const Demo = () => { const size = useWindowSize(); if (size === "small") return <SmallComponent />; else return <LargeComponent />; };
|
有助于关注分离
代码逻辑写在一起