【问题标题】:React Native Render Error - Error: Objects are not valid as a React childReact Native 渲染错误 - 错误:对象作为 React 子级无效
【发布时间】:2021-10-30 17:15:20
【问题描述】:

当我将卡片组件添加到 app.js 时,它显示以下错误:

(错误:对象作为 React 子对象无效(发现:带有键 {} 的对象)。如果您要呈现子对象集合,请改用数组。

我没有添加任何对象来添加键。在 AppText 组件中,我只传递了 children 道具,并将它们用作 Card 组件中的标题和副标题

import React from 'react';
import Card from './app/components/Card';
import {View} from 'react-native';

export default function App() {
  return (
    <View
      style={{
      backgroundColor: '#f8f4f4',
      padding: 20,
      paddingTop: 100,
    }}>
      <Card
        title="Item 1"
        subTitle="$50 Million"
        image={require('./app/assets/image/card-img1.jpg')}
      />
   </View>
 );
}

这是card 组件代码

import React from 'react';
import {Image, StyleSheet, View} from 'react-native';
import colors from '../config/colors';
import AppText from './AppText';

function Card(image, title, subTitle) {
  return (
    <View style={styles.card}>
      <Image source={image} />
      <AppText>{title}</AppText>
      <AppText>{subTitle}</AppText>
    </View>
  );
}

const styles = StyleSheet.create({
  card: {
    borderRadius: 15,
    backgroundColor: colors.white,
    marginBottom: 20,
  },
});

export default Card;

这是AppText 组件

import React from 'react';
import {Text, StyleSheet, Platform} from 'react-native';
import colors from '../config/colors';

function AppText({children}) {
  return <Text style={styles.text}>{children}</Text>;
}

const styles = StyleSheet.create({
  text: {
    color: colors.black,
    ...Platform.select({
      ios: {
        fontSize: 20,
        fontFamily: 'Avenir',
      },
      android: {
        fontSize: 18,
        fontFamily: 'Roboto',
      },
    }),
  },
});

export default AppText;

【问题讨论】:

    标签: javascript react-native


    【解决方案1】:

    一个简单的改变,让它发挥作用!

    从以下位置更改您的 Card 组件定义:

    function Card(image, title, subTitle) {
    

    function Card({image, title, subTitle}) {
    

    解释:

    当你想给一个组件传递属性时,你的组件的输入参数将是porps,如果你想销毁这些props,你需要放一个{}(props是一个对象):

    const myObject = {name: 'testName', title: 'testTitle'}
    
    const {name, title} = myObject
    

    【讨论】:

      【解决方案2】:

      在您的 Card 功能组件中,您应该解构传递给它的道具。

      另外,props在声明和使用中的顺序要一致。

      变化

      发件人:

      function Card(image, title, subTitle)
      

      收件人:

      function Card({title, subtTitle, image})
      

      【讨论】:

        猜你喜欢
        • 2022-09-27
        • 2018-11-12
        • 1970-01-01
        • 2018-10-18
        • 2021-08-20
        • 2019-06-14
        • 2021-08-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多