下面是两个几乎做同样事情的React 组件。一个是函数;另一个是一个类。每个组件都有一个Animated.Value异步侦听器,可_foo在更改时更新。我需要能够_foo像this._foo在经典组件中那样访问功能组件。
FunctionalBar不应该_foo在全局范围内,以防有多个FunctionalBar.FunctionalBar不能_foo在函数范围内,因为_foo每次FunctionalBar渲染时都会重新初始化。_foo也不应该处于状态,因为组件在_foo更改时不需要渲染。ClassBar没有这个问题,因为它在组件的整个生命周期中都保持_foo初始化状态this。
如何_foo在FunctionalBar不将其置于全局范围内的情况下在整个生命周期内保持初始化?
功能实现
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 />;
}
经典实现
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 />;
}
}