随着componentWillReceiveProps被弃用,替换的getDerivedStateFromProps返回最后的状态,我将如何随着时间的推移逐渐改变状态(即动画化的东西)与新的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();
}
}我怎么用getDerivedStateFromProps做这样的事呢?还是我的动画模式太蠢了?
发布于 2018-06-01 11:07:44
getDerivedStateFromProps是用newProps和previousState参数调用的。因此,您可以在动画中使用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
}
}发布于 2018-06-01 18:23:13
简单的答案是不要在动画中使用state (感谢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;
}
}https://stackoverflow.com/questions/50641678
复制相似问题