我有大约<AnimatedButton />

我想动画它从isFullWidth%宽度到40%宽度取决于一个称为isFullWidth的布尔型props .

我有:

class AnimatedButton extends Component {
    constructor(props) {
      super(props);
      this.state = { width: new Animated.Value(100) };
    }
    toggleWidth() {
      const endWidth = this.props.isFullWidth ? 40 : 100;

      Animated.timing(this.state.width, {
        toValue: endWidth,
        duration: 200,
        easing: Easing.linear,
      }).start();
    }

    render() {
      <TouchableOpacity
       style={{ width: `${this.state.width}%` }}
       onPress={this.props.onPress}
      >
       // more stuff
      </TouchableOpacity>
    }
}

问题是,它只是跳转到适当的百分比,而没有设置动画.我试着将宽度设置为this.state.animatedValue,而不是使用百分比,只使用像素,例如150到400以及后面的像素,它可以像预期的那样正常工作.

同样的问题也适用于rgba(220, 100, 50, 0.8)

推荐答案

我建议你阅读更多关于interpolation的内容,因为它在用React Native制作几乎任何类型的动画时都非常有用.

基本上,使用interpolate可以将一些动画值映射到其他值.在本例中,您希望将40-interpolate之间的数字映射为50%之类的百分比字符串.第二件事是将40-interpolate之间的数字映射为红色到蓝色(例如).

全面阅读interpolate docs并进行实验,然后询问是否有问题:)

所以我会这样做:

class AnimatedButton extends Component {
  constructor(props) {
    super(props);
    this.state = { width: new Animated.Value(100) };
  }

  toggleWidth() {
    const endWidth = this.props.isFullWidth ? 40 : 100;

    Animated.timing(this.state.width, {
      toValue: endWidth,
      duration: 200,
      easing: Easing.linear,
    }).start();
  }

  render() {
    <TouchableOpacity
      style={{
        width: this.state.width.interpolate({
          inputRange: [0, 1],
          outputRange: ['0%', '100%'],
        }),
        backgroundColor: this.state.width.interpolate({
          inputRange: [40, 100],
          outputRange: ['rgba(30, 70, 30, 1.0)', 'rgba(220, 100, 50, 0.8)'],
        }),
      }}
      onPress={this.props.onPress}
    >
      // more stuff
    </TouchableOpacity>;
  }
}

React-native相关问答推荐

Touchabble 不透明度不工作-react 本机

React Native 中的视图与 Flex 不占用相同的高度空间

react native 如何更新倒置平面列表的数组中的项目

错误:图片:找不到 ID 为1的assets资源 .请判断图像源或打包器

react-native-fs 改变 toUrl 本身

React-native 重置数据库

React Native:在ScrollView中更改焦点时键盘关闭

在 TouchableOpacity 上创建 Raised凸起或Shadow阴影效果

React.js - 为所有组件方法使用属性初始化器

react native foreach 循环

由于依赖关系,在 run-android 上构建失败

submit提交后如何让 React Native TextInput 保持焦点?

在 React Native 中使用多个上下文提供程序的更好方法

如何在 React Native 中将静态图像拉伸为背景?

有没有办法改变 IOS 标题上react-navigation 的默认后退按钮 colored颜色 ?

如何在 React 中使用带有钩子的生命周期方法?

在 React Native 视图上强制 onLayout

Port 8081 already in use, packager is either not running or not running correctly Command /bin/sh failed with exit code 2

设置 react-native 元素时使用特定的包名称

降级 react-native 的适当机制