弃用componentWillReceiveProps
并且替换getDerivedStateFromProps
返回最终状态,我将如何随着时间的推移逐渐改变状态(即动画内容){{1 }}?
使用getDerivedStateFromProps
,以下工作正常:
componentWillReceiveProps
我如何使用state = {
itemOpacity: new Animated.Value(0.25)
};
componentWillReceiveProps(nextProps) {
if (this.props.items.visible !== nextProps.items.visible) {
let value = 0;
if (nextProps.items.visible) {
value = 1;
}
Animated.timing(this.state.itemOpacity, {
toValue: value,
duration: 200,
}).start();
}
}
执行此类操作?或者我的动画模式是愚蠢的?
答案 0 :(得分:1)
使用newProps和previousState参数调用getDerivedStateFromProps。所以你可以使用previousState作为动画:
static getDerivedStateFromProps(nextProps, prevState) {
let value = 0;
if (nextProps.items.visible) {
value = 1;
}
Animated.timing(prevState.itemOpacity, {
toValue: value,
duration: 200,
}).start();
return {
// update state
}
}
答案 1 :(得分:1)
简单的答案就是不要使用状态来制作动画(感谢dentemm的帮助):
itemOpacity = new Animated.Value(0.25);
class TestScreen extends Component {
getDerivedStateFromProps(nextProps) {
let value = 0;
if (nextProps.items.visible) {
value = 1;
}
Animated.timing(itemOpacity, {
toValue: value,
duration: 200,
}).start();
return null;
}
}