我有一些 <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/