javascript - 我如何根据百分比为按钮的宽度设置动画,它的 backgroundColor 也是如此?

标签 javascript reactjs animation react-native

我有一些 <AnimatedButton />

我想根据一个名为 isFullWidth 的 bool 值将其设置为从 100% 宽度变为 40% 宽度的动画。 .

我有:

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)rgba(30, 70, 30, 1.0)然后回来?

最佳答案

我建议您阅读有关 interpolation 的更多信息因为在 React Native 中做几乎任何类型的动画时它都非常有用。

基本上,使用 interpolate,您可以将一些动画值映射到其他值。在您的情况下,您希望将 40-100 之间的数字映射到百分比字符串,如 50%。您要做的第二件事是将 40-100 之间的数字映射到从(例如)红色到蓝色的颜色。

完整阅读 interpolate 文档并进行实验,然后询问您是否有问题:)

所以我会这样做:

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>;
  }
}

关于javascript - 我如何根据百分比为按钮的宽度设置动画,它的 backgroundColor 也是如此?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48740325/

相关文章:

javascript - 使用 webpack ou npm 在多个包中拆分 javascript Javascript 项目

php - Javascript 和 PHP - 选中和取消选中所有复选框

reactjs - React-admin 在创建 View 提交后保留表单数据

animation - 如何循环SVG动画序列?

javascript - 无限期动画结束事件?

javascript - 如何将输入元素添加到变量

javascript - NativeScript Sidekick 是否会在构建应用程序时删除 XML 和 JavaScript 中的注释并缩小源代码?

javascript - 如何在 Material-UI 中插入新行?

javascript - react 运动的压倒性语法

html - 可以在不播放动画的情况下加载动画 gif 吗?