首页 > 解决方案 > 如何在 React Native 中调用函数

问题描述

不能通过引用使用子函数。

export class Home extends React.Component {
constructor() {
    this.imageReference = React.createRef();
}

state = {
    fadeAnim: new Animated.Value(0),
}

componentDidMount() {
    Animated.timing(
        this.state.fadeAnim,
        {
            toValue: 1,
            duration: 2400,
            useNativeDriver: true
        }
    ).start(() => this.imageReference.current.initImageAnimation());
}

render() {
    let { fadeAnim } = this.state;

    return (
        <View style={{ flex: 1 }}>
            <Animated.View style={{
                opacity: fadeAnim,
                flex: 1,
                backgroundColor: '#7eb3e0',
                justifyContent: 'center',
                alignItems: 'center'
            }}>
                <Logo ref={this.imageReference} />
            </Animated.View>
        </View>
    )
}

发生错误:TypeError: undefined is not an object (evalating '_this.imageReference = _react.default.createRef()')

标签: javascriptandroidreactjsreact-native

解决方案


我相信您在构造函数中缺少 super() 以使您的实例属性起作用:

constructor() {
    super()
    this.imageReference = React.createRef();
}

这个 SO 答案详细解释了为什么: 如何在 ES6 中无需使用 super 来扩展类?


推荐阅读