Как анимировать backgroundColor ScrollView в React Native - PullRequest
0 голосов
/ 15 мая 2018

Я хочу анимировать backgroundColor ScrollView, но всегда получаю предупреждение - и не анимационный ScrollView.Я попал в ошибку?Или это просто не поддерживается в ScrollView?(Он работает в обычном режиме просмотра.) Я тестирую с помощью Expo на iPhone iOS.

Соответствующие фрагменты кода:

<Animated.ScrollView
  contentContainerStyle={[
    styles.container,
    this.getCurrentColorOfBackground()
  ]}>
  <Text onPress={this.onPress} style={styles.question}>
    {this.state.question}
  </Text>
</Animated.ScrollView>

метод getCurrentColorOfBackground ():

  getCurrentColorOfBackground = () => ({
    backgroundColor: this.backgroundColor.interpolate({
      inputRange: [0, 100],
      outputRange: ["#00aaFF", "#808080"]
    })
  });

сама анимация:

this.backgroundColor = new Animated.Value(0);
Animated.timing(this.backgroundColor, {
  toValue: 100,
  duration: 1000 * 60
}).start();

Предупреждающее сообщение:

20: 17: 58: Предупреждение: сбойный тип пропуска: недопустимая опора backgroundColor переданScrollView: [объектный объект] Допустимые цветовые форматы - '# f0f' (#rgb) - '# f0fc' (#rgba) - '# ff00ff' (#rrggbb) - '# ff00ff00' (#rrggbbaa) - 'rgb (255, 255, 255) '-' rgba (255, 255, 255, 1.0) '-' hsl (360, 100%, 100%) '-' hsla (360, 100%, 100%, 1.0) '- 'transparent' - 'red' - 0xff00ff00 (0xrrggbbaa)

Плохой объект: {"flexGrow": 1, "alignItems": "center",
"justifyContent": "center", "backgroundColor":" rgba (0, 170, 255, 1) "} в ScrollView (at createAnimatedComponent.js: 154)

Если вы хотите попробовать сами, полный компонент (и репо) здесь: https://github.com/wim82/chapter-interview/blob/master/QuestionRotator.js

Ответы [ 2 ]

0 голосов
/ 09 октября 2018

Вы не можете анимировать какие-либо свойства contentContainerStyle представления прокрутки, потому что базовый компонент, ScrollContentContainerViewClass, жестко закодирован реагирующим и не может быть изменен. Смотрите исходный код здесь: https://github.com/facebook/react-native/blob/bbb6a0754ce4173e24d3c0b46a5350ff2a8690d3/Libraries/Components/ScrollView/ScrollView.js#L790-L802

Вам необходимо открыть вопрос, а затем отправить запрос на извлечение, добавив свойство в scrollView, которое позволит вам установить ScrollContentContainerViewClass.

0 голосов
/ 16 мая 2018

Примените backgroundColor внутри свойства style вместо contentContainerStyle scrollView.

Animated.Value (0) должен храниться в состоянии, а не как объект класса (из официальных документов и передового опыта).

Я изменил ваш код выше, чтобы он работал,

import React, { Component } from 'react';
import { Text, StyleSheet, Animated } from 'react-native';

export default class App extends Component {


  constructor (props) {
    super(props);
    // Intialize to default value
    this.state = {
      backgroundColor: new Animated.Value(0)
    };
  }

  onPress = () => {
    // onPress, initialize to default value using setState and start animation
    // after the state has been updated
    this.setState({ backgroundColor: new Animated.Value(0) }, () => {
       Animated.timing(this.state.backgroundColor, {
        toValue: 100,
        duration: 5000
      }).start();
    });
  }


  render() {
    return (
      <Animated.ScrollView
        style={[
            styles.container,
            // Interpolation mapping from numbers to strings (colors)
            {
              backgroundColor: this.state.backgroundColor.interpolate({
                inputRange: [0, 100],
                outputRange: ["#00aaFF", "#808080"]
              })
            }
          ]}
      >
        <Text
          // onPress to start Animation
          onPress={() => this.onPress() }
          style={styles.paragraph}
        >
          Change code in the editor and watch it change on your phone!
          Save to get a shareable url.
        </Text>
      </Animated.ScrollView>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  paragraph: {
    margin: 24,
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
    color: '#34495e',
  },
});

Пример рабочего перекуса: https://snack.expo.io/BymzMdtRG

Надеюсь, это поможет.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...