mirror of
https://github.com/facebook/react-native.git
synced 2025-11-01 09:14:26 +00:00
refactor(rn tester app): change dimensions example to hooks (#35084)
Summary: This pull request migrates the dimensions example to using React Hooks. ## Changelog [General] [Changed] - RNTester: Migrate Dimensions to hooks Pull Request resolved: https://github.com/facebook/react-native/pull/35084 Test Plan: The animation works exactly as it did as when it was a class component Reviewed By: yungsters Differential Revision: D40779014 Pulled By: NickGerleman fbshipit-source-id: e740684d3022a945da5abc33b2e8834c6cfabb97
This commit is contained in:
committed by
Facebook GitHub Bot
parent
07bd590843
commit
745e26288c
@@ -8,38 +8,24 @@
|
||||
* @flow
|
||||
*/
|
||||
|
||||
import type {EventSubscription} from 'react-native/Libraries/vendor/emitter/EventEmitter';
|
||||
import {Dimensions, Text, useWindowDimensions} from 'react-native';
|
||||
import * as React from 'react';
|
||||
import {useState, useEffect} from 'react';
|
||||
|
||||
class DimensionsSubscription extends React.Component<
|
||||
{dim: string, ...},
|
||||
{dims: Object, ...},
|
||||
> {
|
||||
state: {dims: any, ...} = {
|
||||
dims: Dimensions.get(this.props.dim),
|
||||
};
|
||||
type Props = {dim: string};
|
||||
|
||||
_dimensionsSubscription: ?EventSubscription;
|
||||
function DimensionsSubscription(props: Props) {
|
||||
const [dims, setDims] = useState(() => Dimensions.get(props.dim));
|
||||
|
||||
componentDidMount() {
|
||||
this._dimensionsSubscription = Dimensions.addEventListener(
|
||||
'change',
|
||||
dimensions => {
|
||||
this.setState({
|
||||
dims: dimensions[this.props.dim],
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
useEffect(() => {
|
||||
const subscription = Dimensions.addEventListener('change', dimensions => {
|
||||
setDims(dimensions[props.dim]);
|
||||
});
|
||||
|
||||
componentWillUnmount() {
|
||||
this._dimensionsSubscription?.remove();
|
||||
}
|
||||
return () => subscription.remove();
|
||||
}, [props.dim]);
|
||||
|
||||
render(): React.Node {
|
||||
return <Text>{JSON.stringify(this.state.dims, null, 2)}</Text>;
|
||||
}
|
||||
return <Text>{JSON.stringify(dims, null, 2)}</Text>;
|
||||
}
|
||||
|
||||
const DimensionsViaHook = () => {
|
||||
|
||||
Reference in New Issue
Block a user