React Native中Animated组件实现View宽度动画失效问题求助
Hey there, let's get that width animation working for you! I've spotted a couple of key issues in your code that are stopping the animation from running properly:
1. Critical Typo in Lifecycle Method
The biggest problem is a misspelled lifecycle method: you wrote compontentDidMount instead of componentDidMount. React doesn't recognize this misspelled name, so the animation code inside never gets triggered at all. That's why your width isn't changing—your animation never even starts!
You also have a small typo in your HomeScreen class definition (Componen instead of Component) which would throw a syntax error if left uncorrected.
2. Corrected Full Code
Here's the fixed version of your code with these issues addressed, plus a few helpful tweaks:
import React, { Component } from 'react'; import { Animated, View, Text } from 'react-native'; class MyView extends Component { state = { theWidth: new Animated.Value(10), } // Fixed lifecycle method name componentDidMount() { Animated.timing( this.state.theWidth, { toValue: 100, duration: 10000, // Explicitly set useNativeDriver to false (required for layout props like width) useNativeDriver: false, } ).start(); } render() { let { theWidth } = this.state; return ( <Animated.View style={{ ...this.props.style, width: theWidth, // Added background color to make the width change visible backgroundColor: 'lightblue', padding: 10, }} > {this.props.children} </Animated.View> ); } } // Fixed Component spelling export default class HomeScreen extends Component { render() { return ( <View style={{ flex: 1, padding: 20, marginTop: 60 }}> <MyView> <Text>Watch my width grow!</Text> </MyView> </View> ); } }
Quick Additional Notes
- I added
useNativeDriver: falseto the animation config: Native driver doesn't support layout properties likewidth, so setting this explicitly avoids warnings and ensures the animation works as expected. - The background color and padding are just to make the width change more obvious—you can remove or modify those to match your design.
- Double-check that you've imported all required components (
Text,View,Animated) fromreact-nativeto avoid undefined errors.
Once you update your code with these fixes, your view should smoothly expand from 10 to 100 units over 10 seconds, just like you intended.
内容的提问来源于stack exchange,提问作者William Hu

