如何在React Native中将函数从Context传递到App.js?

pftdvrlh  于 2022-11-25  发布在  React
关注(0)|答案(1)|浏览(93)

当我运行应用程序时,错误消息显示TypeError: undefined is not an object (evaluating '_useContext.state')
下面是我的App.js:

import React from 'react'
import { StatusBar } from 'expo-status-bar';
import { useState, useEffect, useContext } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { Context as ActivitiesContext, Provider } from "./context/ActivitiesContext";

const App = () => {

  const { state, getActivity } = useContext(ActivitiesContext);

  useEffect(() => {
    getActivity()
  }, []);

  return (
    <View style={styles.container}>
      <Text>Open App.js to start working on your file</Text>
      <StatusBar style="auto" />
    </View>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

export default App

下面是我的ActivitiesContext.js:

import createDataContext from "./CreateDataContext";

const getActivity = () => {
  return console.log("hi");
};

export const { Provider, Context } = createDataContext(
  {
    getActivity,
  }
);

下面是我的CreateDataContext.js

import React, { useReducer } from 'react';

export default (reducer, action, defaultValue) => {
    const Context = React.createContext();

    const Provider = ({ children }) => {
        const [state, dispatch] = useReducer(reducer, defaultValue);

        const boundActions = {};

        for (let key in action) {
            boundActions[key] = action[key](dispatch);
        }

        return (
            <Context.Provider value={{ state, ...boundActions }}>
                {children}
            </Context.Provider>
        )
    };

    return { Context: Context, Provider: Provider };
};

我希望将getActivity函数中的console.log("hi")传递给App.js和控制台日志“hi”。
还有提供者,它的目的是什么,我如何使用它?我想这就是我所缺少的。

2cmtqfgy

2cmtqfgy1#

1.创建context
1.使用Provider通过 Package 组件来传递值,以提供对树中更深层次组件的访问
1.使用useContext访问任何组件的值

const ThemeContext = React.createContext(); // 1.

const App = () => {
  // 2.
  return <ThemeContext.Provider value={{color: 'black', getColor: () => 'red'}}> 
      <MyComponet />
    </ThemeContext.Provider>
}

const MyComponet = () => {
  return (
    <View>
      <MyButton />
    </View>
  );
}

const MyButton = () => {
  const theme = useContext(ThemeContext) // 3.
 
  return <Button title="Button" color={theme.getColor()}/>;
}

相关问题