从根组件反应本机访问功能

时间:2020-07-02 17:51:19

标签: javascript reactjs react-native react-context

在我的React Native应用程序中,我当前正在开发自定义吐司。我的应用程序的根本是我的吐司组件。我希望能够在我的应用程序中的任何位置调用此特定组件callToast()函数。我试图建立一个存储该根组件的引用的上下文,然后通过我的应用程序中任何位置的使用者访问该上下文,但是它不起作用。我的第一个迭代如下所示:

应用/根屏幕

export const ToastContext = React.createContext()

export const useToast = () => {
   return ToastContext.toastRef;
};


state = {
        ref : null
    };
<ToastContext.Provider value = {this.state.ref}>
  <>
    <AppContainer />
    <Toast ref = {r => this.setState({ref : r})}/>
  </>
</ToastContext.Provider>

我的吐司成分

import React, {useRef, useState, useEffect} from 'react';
import {
  View,
  Text,
  StyleSheet, Dimensions, Image, TouchableOpacity, Animated
} from 'react-native';


const {width, height} = Dimensions.get('window')

const HEIGHT_OF_TOAST = 60
let TOAST_REF;

export const Toast = ({}) => {

  const animate = useRef(new Animated.Value(0)).current
  const animateInOut = animate.interpolate({
    inputRange : [0,1],
    outputRange : [-(HEIGHT_OF_TOAST + 10), 30]
  })
  const callToast = () => {
    Animated.timing(animate, {
      toValue : 1,
      duration : 200
    }).start()
  }

  return (
    <Animated.View style = {[styles.shadow,
        {position : 'absolute', opacity : animate, bottom : animateInOut, right : 20, borderRadius : 12, left : 20,
          backgroundColor : "#fff", height : HEIGHT_OF_TOAST}]}>
      <Text>Toast</Text>
    </Animated.View>

  )
}


const styles = StyleSheet.create({
  shadow : {
    shadowColor: "#333",
    shadowOffset: {
        width: 0,
        height: 4,
    },
    shadowOpacity: 0.4,
    shadowRadius: 7.2,

    elevation: 9,
  }
})


我试图称呼吐司的虚拟部件

//At start of component
const toast = useToast()


<TouchableOpacity onPress = {() => toast.callToast()}>
              <Text>Test Toast</Text>
            </TouchableOpacity>

尝试执行此操作时,出现错误:undefined不是评估toast.callToast的对象

从上下文使用者使用它时,我得到一个context.value是未定义的错误。 对于提供某种功能的任何帮助或最佳实践,我们将不胜感激。

0 个答案:

没有答案