【问题标题】:Implementing Native base in React Native functional component with react hooks in Expo在 Expo 中使用 React 钩子在 React Native 功能组件中实现 Native 基础
【发布时间】:2020-09-02 08:38:22
【问题描述】:

我正在尝试在 Expo 中使用带有功能组件的 Native 基础库。但是,Native 基础文档展示了如何在 Class 组件中使用它,如下所示:

import React from 'react';
import { AppLoading } from 'expo';
import { Container, Text } from 'native-base';
import * as Font from 'expo-font';
import { Ionicons } from '@expo/vector-icons';

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isReady: false,
    };
  }

  async componentDidMount() {
    await Font.loadAsync({
      Roboto: require('native-base/Fonts/Roboto.ttf'),
      Roboto_medium: require('native-base/Fonts/Roboto_medium.ttf'),
      ...Ionicons.font,
    });
    this.setState({ isReady: true });
  }

  render() {
    if (!this.state.isReady) {
      return <AppLoading />;
    }

    return (
      <Container>
        <Text>Open up App.js to start working on your app!</Text>
      </Container>
    );
  }
}

我尝试转换的方法如下:

import { StatusBar } from "expo-status-bar";
import React, { useState, useEffect } from "react";
import { StyleSheet, View } from "react-native";

import { AppLoading } from "expo";
import * as Font from "expo-font";
import { Ionicons } from "@expo/vector-icons";

import { Container, Text } from "native-base";

export default function App() {
  [isReady, setReady] = useState(false);
  const app = !isReady ? (
    <AppLoading />
  ) : (
    <Container>
      <Text>Open up App.js to start working on your app!</Text>
    </Container>
  );
  return app;
}

async function native_base() {
  await Font.loadAsync({
    Roboto: require("native-base/Fonts/Roboto.ttf"),
    Roboto_medium: require("native-base/Fonts/Roboto_medium.ttf"),
    ...Ionicons.font,
  });
}
useEffect(() => {
  native_base();
  setReady(true);
});

并得到错误提示“Hooks 只能在函数组件的主体内部使用”

【问题讨论】:

    标签: reactjs react-native expo native-base


    【解决方案1】:

    你在函数外使用了 useEffect 钩子,所以你得到了那个错误

    export default function App() {
      [isReady, setReady] = useState(false);
      useEffect(() => {
      native_base();
      setReady(true);
       });
      const app = !isReady ? (
        <AppLoading />
      ) : (
        <Container>
          <Text>Open up App.js to start working on your app!</Text>
        </Container>
      );
      return app;
    }
    
    async function native_base() {
      await Font.loadAsync({
        Roboto: require("native-base/Fonts/Roboto.ttf"),
        Roboto_medium: require("native-base/Fonts/Roboto_medium.ttf"),
        ...Ionicons.font,
      });
    }
    
    

    【讨论】:

      猜你喜欢
      • 2021-06-14
      • 2017-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-08
      • 2021-04-04
      • 2020-09-10
      相关资源
      最近更新 更多