首页 > 解决方案 > Text Tag React Native 中的函数

问题描述

我遇到了 react-native Text 标签的问题。我不知道为什么会这样。请帮忙。我需要在Text 标记内使用函数 retrieveData ,但这会产生错误。我究竟做错了什么?谢谢我在另一个文件中使用 AsyncStorage 设置了数据(mobileNumber 作为键)。

import React, { Component } from "react";
import {
  View,
  Text,
  TextInput,
  SafeAreaView,
  TouchableOpacity,
  AsyncStorage
} from "react-native";

export default class PhoneCode extends Component {
  constructor(props) {
    super(props);
    this.state = {
    };
  }
  onVerify = () => {};
  onPress = () => {
    alert("Sending...");
  };
  tappedVerify = () => {
    console.log("clicked")
  };
  render() {
    const { code, isCodeValid } = this.state;
    const _retrieveData = async () => {
      try {
        const value = await AsyncStorage.getItem("mobileNumber");
        if (value !== null) {
          // We have data!!
          return value;
        }
      } catch (error) {
        // Error retrieving data
        console.log("failed");
      }
    };
    return (
      <SafeAreaView style={styles.container}>
        <View style={styles.contentArea}>
          <Text style={{}}> Enter... </Text>

          <View style={styles.codeArea}>
            <Text style={styles.codeInput}> {_retrieveData()} </Text> // this is the problem

            <TextInput
              placeholder="Enter here"
              underlineColorAndroid="transparent"
              style={styles.textInput}
              maxLength={6}
              autoGrow={true}
              maxHeight={40}
              keyboardType={"phone-pad"}
              onChangeText={(text) =>
                this.setState({
                  //....
                })
              }
            />
          </View>
       </View>
      </SafeAreaView>

这是样式对象

const styles = StyleSheet.create({
   container: {
    flex: 1,
    justifyContent: "flex-start",
    alignItems: "center"
  },
  contentArea: {
    justifyContent: "flex-start",
    alignItems: "center",
    width: '100%',
    height: '100%',
    paddingTop: 80,
    paddingLeft: 20,
    paddingRight: 20
  },
 textInput: {
    textAlign: 'center',
    height: 50,
    width: '18%',
    borderWidth: 2,
    borderColor: 'gray',
    borderRadius: 20,
    backgroundColor: "#FFFFFF"

  }
})

这是错误消息

ExceptionsManager.js:74 Invariant Violation: Objects are not valid as a React child (found: object with keys {_40, _65, _55, _72}). If you meant to render a collection of children, use an array instead.

标签: javascriptreact-native

解决方案


这样做可以解决我的问题。它可能会帮助别人。

<Text style={styles.codeInput}> {`${_retrieveData()}`} </Text>

推荐阅读