反应本地不传递组件之间的道具?

时间:2020-01-14 15:57:33

标签: javascript reactjs react-native

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

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

为什么不起作用?

2 个答案:

答案 0 :(得分:0)

问题是这一行:

const {children} = this.props.titleProperty;

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

上进行销毁的更多信息

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

答案 1 :(得分:0)

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

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

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

您可以通过多种方式执行此操作,下面列出了其中的几种

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

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

Find output here

相关问题