VDo*_*Dog 8 javascript animation reactjs react-native
我有一些 <AnimatedButton />
我希望动画它从100%宽度变为40%宽度,具体取决于被称为布尔值的道具isFullWidth.
我有:
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>
}
}
Run Code Online (Sandbox Code Playgroud)
问题是它只是在没有动画的情况下跳到适当的百分比.我尝试将宽度设置为正好this.state.animatedValue而不是使用百分比,只使用像素,例如150到400并返回,并且它按预期工作正常.
同样的问题适用于打算从说rgba(220, 100, 50, 0.8)要rgba(30, 70, 30, 1.0)和背?
Hen*_*k R 22
我建议你阅读更多关于插值的内容,因为它在React Native中做几乎任何类型的动画时非常有用.
基本上interpolate你可以将一些动画值映射到其他值.在您的情况下,您希望将数字在40-100之间映射到百分比字符串之类50%.你要做的第二件事是将40-100之间的数字映射到从红色到蓝色的颜色(例如).
完全阅读插入文档并进行实验并询问之后是否有问题:)
所以我会这样做:
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%', '1%'],
}),
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>;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7275 次 |
| 最近记录: |