Add Animated.useCode hook as an alternative to Animated.Code (#237)

* add useCode hook as an alternative to Animated.Code

* Add useCode documentation to README

Added a short description of Animated.useCode to the README, with both a function signature and an example of its use in a component.
This commit is contained in:
Jeremy Deutsch
2019-04-15 04:12:09 -07:00
committed by Michał Osadnik
parent cc9787b110
commit 0882c97e82
4 changed files with 37 additions and 0 deletions

View File

@@ -220,6 +220,21 @@ block([
}/>
```
## `Animated.useCode`
The `useCode` hook acts as an alternative to the `Animated.Code` component.
```js
Animated.useCode(node, deps)
```
It's passed an animated node and an array of dependencies, and updates that node both when the component mounts and every time a value in that array changes. It does nothing on versions of React Native that don't support hooks (<0.59).
```js
const [offset, setOffset] = React.useState(20);
Animated.useCode(
set(transX1, add(_transX, offset)),
[offset]
);
```
## Event handling with reanimated nodes
`react-native-reanimated`'s new syntax is possible to be used with `Animated.event`. Instead of providing only a mapping from event fields to animated nodes, it is allowed to write a function that takes reanimated values map as an input and return a block (or any other reanimated function) that will be then used to handle the event.

View File

@@ -278,6 +278,12 @@ declare module 'react-native-reanimated' {
config: DecayConfig,
): BackwardCompatibleWrapper;
// hooks
export function useCode(
exec: AnimatedNode<number>,
deps: Array<any>,
): void
// configuration
// `addWhitelistedNativeProps` will likely be removed soon, and so is

View File

@@ -9,3 +9,4 @@ export { default as min } from './min';
export { default as onChange } from './onChange';
export { default as floor } from './floor';
export { default as ceil } from './ceil';
export { default as useCode } from './useCode';

15
src/derived/useCode.js Normal file
View File

@@ -0,0 +1,15 @@
import React from 'react';
import { always } from '../base';
function useCode(exec, deps) {
if (typeof React.useEffect === 'function') {
React.useEffect(() => {
const animatedAlways = always(exec);
animatedAlways.__attach();
return () => {
animatedAlways.__detach();
};
}, deps);
}
}
export default useCode;