1

I’m currently using LayoutAnimation to animate a view when children are added. However, since LayoutAnimation causes everything to be animated, globally, and I can’t easily use built-in Animated library to fit my use-case, I’m wondering if react-native-reanimated is able to help.

Here's a snack of my current solution: https://snack.expo.io/@insats/height-adapation

This is what the result of that looks like:

enter image description here

Is there a way to achieve the same thing without using LayoutAnimation? I've looked through all exampled in react-native-reanimated, and I've read through the docs but I'm still not sure if this is possible to do or how I should get started. I've thought about using Animated to move the item-wrapper out of the viewable area and "scroll" it upwards (using transform translateY) when items are added, but that would require fixed height, which I don't have.

4

1 回答 1

3

我有两种方法可以建议:

  1. LayoutAnimation仅当所需状态发生更改时,您才可以配置。如果你使用钩子,那就太容易了:

    const [state,setState] = useState([]);
    useEffect(()=>{
       /*rest code*/
       LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut)
    },[state])
    

    或者,如果您使用类组件,您可以在以下位置捕获所需的状态变化componentDidUpdate

    componentDidUpdate(prevProps,prevState){
       if(prevState.items!==state.items){
           LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut)
       }
    }
    
  2. 您可以使用onLayout视图功能:

    addItem = () => {
       this.setState({
          items: [...this.state.items, {title:'An item',isNew:true}]
       })
    }; 
    renderItems = () => {
       return this.state.items.map((item, index) => {
          let opacity = new Animated.Value(0);
          return (
            <Animated.View onLayout={({nativeEvent})=>{
               if(this.state.item.isNew){
                  // here you got the height from nativeEvent.layout.height
                  // Then you have to store the height animate height and opacity to its precise value 
                  // PS I used opacity:0 to calculate the height
                 }
               }} key={index} style={[styles.item,{opacity}>
              <Text>{item.title}</Text>
            </View>
           )
       });
    };
    

说到我认为它是's库react-native-reanimated的更快版本。因此,无论哪种方式,您都必须计算高度!react-nativeAnimated

于 2019-12-09T19:35:08.670 回答