下面是两个具有相同功能的react 组分.一个是函数;另一个是班级.每个组件都有一个Animated.Value
,带有一个异步侦听器,可以在发生更改时更新_foo
.我需要能够在功能组件中访问_foo
,就像在classic 组件中访问this._foo
一样.
- 如果
FunctionalBar
个以上,则全局的FunctionalBar
个不应包含_foo
个. -
FunctionalBar
不能在函数作用域中包含_foo
,因为每次FunctionalBar
渲染时都会重新初始化_foo
._foo
也不应处于状态,因为组件在_foo
更改时不需要渲染. -
ClassBar
没有这个问题,因为它在组件的整个生命周期内保持_foo
在this
上初始化.
如何在FunctionalBar
的整个生命周期中保持_foo
的初始化,而不将其置于全局范围内?
功能实现
import React from 'react';
import { Animated, View } from 'react-native';
var _foo = 0;
function FunctionalBar(props) {
const foo = new Animated.Value(0);
_onChangeFoo({ value }) {
_foo = value;
}
function showFoo() {
let anim = Animated.timing(foo, { toValue: 1, duration: 1000, useNativeDriver: true });
anim.start(() => console.log(_foo));
}
useEffect(() => {
foo.addListener(_onChangeFoo);
showFoo();
return () => foo.removeListener(_onChangeFoo);
});
return <View />;
}
classic 实现
import React from 'react';
import { Animated, View } from 'react-native';
class ClassBar extends React.Component {
constructor(props) {
super(props);
this.state = { foo: new Animated.Value(0) };
this._foo = 0;
this._onChangeFoo = this._onChangeFoo.bind(this);
}
componentDidMount() {
this.state.foo.addListener(this._onChangeFoo);
this.showFoo();
}
componentWillUnmount() {
this.state.foo.removeListener(this._onChangeFoo);
}
showFoo() {
let anim = Animated.timing(this.state.foo, { toValue: 1, duration: 1000, useNativeDriver: true });
anim.start(() => console.log(this._foo));
}
_onChangeFoo({ value }) {
this._foo = value;
}
render() {
return <View />;
}
}