如何在外部组件调用中运行Animated.Spring



我正试图从父组件调用Animated.Spring,但函数未运行。你如何解决这个问题?

它在组件内工作,但在从外部调用时不工作。我使用警报来显示函数代码确实运行,但由于某种原因,它跳过了Animated调用。

这是我的代码:

import React, { Component } from 'react'
import { View, Animated, Button, Easing } from 'react-native'
export default class App extends Component {
  handlerSimpleCall = () => {
    //Calling a function of other class (without arguments)
    new Alerts().handleAnimation();
  };
  render() {
    return (
      <View
        style={{
          justifyContent: 'center',
          alignItems: 'center',
          flex: 1,
          backgroundColor: '#F5FCFF',
        }}>
        <Alerts />
        <View style={{ margin: 10 }}>
          <Button
            title="Function Without Argument"
            onPress={this.handlerSimpleCall}
            color="#606070"
          />
        </View>
      </View>
    );
  }
}
class Alerts extends Component {
constructor(props) {
super(props);
this.animatedValue = new Animated.Value(1)
}
handleAnimation = () => {
this.animatedValue.setValue(0)
alert("ASD")
Animated.spring(this.animatedValue, {
toValue: 1,
useNativeDriver: true,
friction: 1
}).start()
}
render() {
return (
<View style={{ height: '100%', width: '100%', justifyContent: "center", alignItems: "center" }}>
<Animated.View style={{ height: 150, width: 150, backgroundColor: 'red', transform: [{ scale: this.animatedValue }] }} />
<View style={{ width: 100, marginTop: 20 }}>
<Button onPress={this.handleAnimation} title='Press Me' />
</View>
</View>
)
}
}

您应该使用ref来引用组件,而不是创建new Alerts()

我能够让它像这样工作:

import React, { Component } from 'react'
import { View, Animated, Button, Easing } from 'react-native'
export default class App extends Component {
constructor(props) {
super(props);
this.alertRef = React.createRef();
}
render() {
return (
<View
style={{
justifyContent: 'center',
alignItems: 'center',
flex: 1,
backgroundColor: '#F5FCFF',
}}>
<Alerts
ref={this.alertRef}
/>
<View style={{ margin: 10 }}>
<Button

title="Function Without Argument"
onPress={() => this.alertRef.current.handleAnimation()}
color="#606070"
/>
</View>
</View>
);
}
}
class Alerts extends Component {
constructor(props) {
super(props);
this.animatedValue = new Animated.Value(1)
}
handleAnimation = () => {
this.animatedValue.setValue(0)
alert("ASD")
Animated.spring(this.animatedValue, {
toValue: 1,
useNativeDriver: true,
friction: 1
}).start()
}
render() {
return (
<View style={{ height: '100%', width: '100%', justifyContent: "center", alignItems: "center" }}>
<Animated.View style={{ height: 150, width: 150, backgroundColor: 'red', transform: [{ scale: this.animatedValue }] }} />
<View style={{ width: 100, marginTop: 20 }}>
<Button onPress={this.handleAnimation} title='Press Me' />
</View>
</View>
)
}
}

最新更新