【问题标题】:Pass props from Parent to child component将道具从父组件传递给子组件
【发布时间】:2018-09-10 16:37:38
【问题描述】:

我有一个父类

import React, { Component } from 'react';
import { View, TouchableOpacity, Text, ListView } from 'react-native';
import Profile from './UserBlock';    

export default class ControlPanel extends Component {
      constructor(props){
        super(props)
        console.log(this.props)
        this.state = {
          email: "email@gg.com",
          first_name: "User",
          image : '../img/user.png'
        }
      }

      render() {
        return(
        <View style={{backgroundColor:'rgba(255,255,255,0.93)', flex:1,}}>
          <Profile {...this.props} />
        </View>)
      }
    }

和子组件

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

    export default class UserBlock extends Component {
              constructor(props){
                super(props)
                this.state = {}
              }

              render() {
                return(
                <View style={{flexDirection:'row', padding:10}}>
                    <Image source ={{uri : this.props.state.image}} resizeMode="contain" style={{margin:15, width:60, height:60, borderRadius:30}} /> 
                    <View style ={{justifyContent:'center', margin:15}}>
                    <Text style={{fontWeight:'700', fontSize:25, color:'#444'}}>{this.props.state.first_name}</Text>
                    <Text style={{fontWeight:'200', color:'#999'}}>{this.props.state.email}</Text>
                    </View>
                </View>)
              }
            }

但是当我尝试读取父道具时,我遇到了一个错误“TypeError: undefined is not an object”
但在我看来,我做的一切都是正确的。

【问题讨论】:

    标签: reactjs react-native react-redux


    【解决方案1】:

    您没有正确地将道具传递给子组件。

    您所做的是使用扩展运算符传递多个键/值,但如果您的道具为空,则不会传递任何内容。

    <Profile {...this.state} />
    

    一样
    <Profile
      email={this.state.email}
      first_name={this.state.first_name}
      image={this.state.image}
    />
    

    要将父状态放入子组件需要做的事情:

    <Profile {...this.state} />
    

    然后在你的子组件中

    console.log(this.props) // would log:
    // email: "email@gg.com"
    // first_name: "User"
    // image : '../img/user.png'
    

    【讨论】:

      【解决方案2】:

      Karl 提到的传递状态是对的,但是子组件也有问题。

      在您的子组件中 - 将 this.props.state.xxxx 替换为 this.props.xxxx,其中 xxxx 是您的电子邮件/名字/图像。

      这应该可以解决问题。

      (可选建议:如果您想更简单 - 将您的子状态与父道具映射,以便您可以根据需要更改并反馈父级)

      这是一个代码沙箱供参考: https://codesandbox.io/embed/9o4vqy4104?module=%2Fsrc%2FuserBlock.js

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-07-04
        • 2020-11-23
        • 2021-01-16
        • 2020-09-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多