mirror of
https://github.com/zhigang1992/react-native-reanimated.git
synced 2026-01-12 17:42:44 +08:00
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:
committed by
Michał Osadnik
parent
cc9787b110
commit
0882c97e82
15
README.md
15
README.md
@@ -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.
|
||||
|
||||
6
react-native-reanimated.d.ts
vendored
6
react-native-reanimated.d.ts
vendored
@@ -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
|
||||
|
||||
@@ -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
15
src/derived/useCode.js
Normal 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;
|
||||
Reference in New Issue
Block a user