簡體   English   中英

React Native 不在組件之間傳遞道具?

[英]React native not passing props between components?

我有一個簡單的容器組件,它應該在某個時候處理一些邏輯:

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',
    },
})

我得到的結果是一個沒有任何文字的藍色條

圖片鏈接

為什么它不起作用?

問題是這一行:

const {children} = this.props.titleProperty;

通過這種方式,您試圖解構titleProperty ,它應該是一個對象並且應該具有children屬性。 更多關於MDN 上的解構

我不確定您是否對 React 的children道具感到困惑,在這種情況下,我建議您閱讀此答案: https : //stackoverflow.com/a/49706920/9013688

它不起作用的原因是因為在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

在此處查找輸出

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM