【问题标题】:React native not passing props between components?React native 不在组件之间传递道具?
【发布时间】:2020-05-01 09:31:09
【问题描述】:

我有一个简单的容器组件,它应该在某些时候处理一些逻辑:

import React, {Component} from 'react';
import {Text, View, Button, Image} from 'react-native';
import Title from '../Presentational/Title';

class AppList extends React.Component {
    render() {
      return (
        <Title titleProperty={'To Do Something'}></Title>
      );
    }
  }

  export default AppList;

我尝试将一些 props 传递给 Title 组件,以便该组件显示它们:

import React, {Component} from 'react'
import {View, Text, StyleSheet} from 'react-native'

export default class Title extends React.Component {
    render() {
        const {children} = this.props.titleProperty;

    return (
        <View style = {styles.header}>
            <Text style={styles.title}>{children}</Text>
        </View>
    )
    }
}

const styles = StyleSheet.create({
    header: {
        backgroundColor: 'skyblue',
        padding: 15,
    },
    title: {
        textAlign: 'center',
        color: 'white',
    },
})

我得到的结果是一个没有任何文字的蓝条

imgur link

为什么它不起作用?

【问题讨论】:

  • 尝试在声明中删除 children 周围的花括号。比如const children = this.props.titleProperty。

标签: javascript reactjs react-native


【解决方案1】:

它不起作用的原因是因为在 Title.js 中,您试图错误地获取 titleProperty 的值。

const {children} = this.props.titleProperty; 表示您要将this.props.titleProperty.children 的值存储在children 常量内。

您应该做的是读取titleProperty 的值,然后它将在您的组件中正确显示。

您可以通过多种方式做到这一点,下面列出了其中的几个

  • const children = this.props.titleProperty;
  • const { titleProperty } = this.props;

在第一个选项中,您可以从 props 中读取 titleProperty 并将其分配给您想要的任何命名变量。在后面的选项中,它将从 this.props 读取 key 的值,并且只分配 key 的值,否则 undefined

Find output here

【讨论】:

    【解决方案2】:

    问题出在这一行:

    const {children} = this.props.titleProperty;
    

    通过这种方式,您试图解构 titleProperty,它应该是一个对象并且应该具有 children 属性。 在MDN了解更多关于解构的信息

    我不确定你是否对 React 的 children 属性感到困惑,在这种情况下,我建议你阅读这个答案:https://stackoverflow.com/a/49706920/9013688

    【讨论】:

      猜你喜欢
      • 2017-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-25
      • 2017-03-11
      • 1970-01-01
      • 2018-05-22
      • 2017-09-24
      相关资源
      最近更新 更多