防止React Native重新安装更改层次结构的键控组件(LayoutAnimation所需)

时间:2019-01-22 22:09:36

标签: react-native layout-animation

我有两个“屏幕”-屏幕A和屏幕B。屏幕A上有一个<RedBox key='thing' />。屏幕B具有相同的组件,但包裹在<View>中。

屏幕A:

<RedBox key='thing' size={100} />

屏幕B:

<View>
   <RedBox key='thing' size={200} />
</View>

通过简单的状态更改将屏幕A和屏幕B换出。

看来,即使<RedBox />具有相同的密钥,由于其层次结构,它也被视为不同的组件。有没有办法强迫RN将它们视为相同的组件并且重新渲染?

我正在尝试使用LayoutAnimation,但是它只能对认为在渲染之间相同的组件进行动画处理。

https://snack.expo.io/@nathanziarek/thing-tester

import * as React from 'react';
import { Text, View, TouchableOpacity, LayoutAnimation } from 'react-native';
import { Constants } from 'expo';

export default class App extends React.PureComponent {
  state = {
    toggle: true,
  };
  render() {
    return (
      <View style={{ marginTop: 200, flex: 1 }}>
        <TouchableOpacity
          onPress={() => {
            LayoutAnimation.configureNext(LayoutAnimation.Presets.spring);
            this.setState({ toggle: !this.state.toggle });
          }}>
          <Text>TAP HERE</Text>
        </TouchableOpacity>
        <Text>Will not animate...</Text>
        {this.state.toggle ? (
          <View>
            <Thing size={100} key="thing" />
          </View>
        ) : (
          <Thing size={200} key="thing" />
        )}

        <Text>Will animate...</Text>

        {this.state.toggle ? (
            <Thing size={100} key="thing2" />
        ) : (
          <Thing size={200} key="thing2" />
        )}
        
      </View>
    );
  }
}

class Thing extends React.PureComponent {
  componentDidMount() {
    console.log('componentDidMount', this.props.size);
  }
  componentDidUnmount() {
    console.log('componentDidUnmount', this.props.size);
  }
  render() {
    return (
      <View
        style={{
          backgroundColor: 'red',
          width: this.props.size,
          height: this.props.size,
        }}
      />
    );
  }
}

0 个答案:

没有答案