【问题标题】:React native - create one common function that can be shared between 2 or more screensReact native - 创建一个可以在 2 个或更多屏幕之间共享的通用功能
【发布时间】:2022-01-21 20:53:16
【问题描述】:

我有 2 个屏幕,SignUpScreen 和 CreateCommunityScreen,这两个屏幕有一个图标,只要单击该图标,就会调用相同的函数 pickImage。如何为两个屏幕创建一个功能?到目前为止,这是我所拥有的,但我遇到了错误“错误:您试图在一个本应不可变且已被冻结的对象上设置键 _V 和值 1。”提前致谢。

pickImage函数

import * as ImagePicker from "expo-image-picker";

const pickImage = async () => {
  let imageURI = "";
  const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();

  if (status === "granted") {
    let selectedImage = await ImagePicker.launchImageLibraryAsync({
      allowsEditing: true,
      aspect: [4, 3],
      quality: 1,
    });

    if (!selectedImage.cancelled) {
      imageURI = selectedImage.uri;
    }

    return imageURI;
  }
};

export default pickImage;

注册屏幕

import React, { useState } from "react";
import { View, Text, Image, StyleSheet } from "react-native";
import AppBrand from "../../component/AppBrand";
import AuthenticationForm from "../../component/AuthenticationForm";
import CustomButtonLink from "../../component/CustomButtonLink";
import DefaultProfileIcon from "../../component/DefaultProfileIcon";
import pickImage from "../../helper/pickImage";

const SignUpScreen = ({ navigation }) => {
  const [image, setImage] = useState(null);

  return (
    <View>
      <AppBrand />
      <DefaultProfileIcon
        onPress={() => {
          setImage(pickImage);
          console.log(image);
        }}
      />
      <AuthenticationForm
        btnName={"SIGN UP"}
        onNavigate={() => {
          console.log("image", image);
          console.log("Stays on Sign Up");
        }}
      />
      <CustomButtonLink
        custBtnLinkName={"Cancel"}
        style={styles.spacing_Cancel}
        onNavigate={() => {
          navigation.navigate("Sign In");
        }}
      />
      {image && (
        <Image source={{ uri: image }} style={{ width: 200, height: 200 }} />
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  spacing_Cancel: {
    marginTop: 170,
    alignItems: "center",
  },
});

export default SignUpScreen;

【问题讨论】:

    标签: javascript reactjs react-native function


    【解决方案1】:

    创建一个包含所有常用函数的文件(例如 Helper.js) 在帮助文件中添加函数并将其导出

    export function getIcon(){
      Console.log("Get icon function called")
        
      }
    

    现在导入你想在不同屏幕中使用的文件

    例如: import Helper from '..path of the file'

    并像使用它

    Helper.getIcon()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-30
      • 1970-01-01
      • 2021-10-25
      相关资源
      最近更新 更多