将道具从父组件传递到子组件

Tar*_*nko 1 reactjs react-native react-redux

我有一个家长班

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>)
      }
    }
Run Code Online (Sandbox Code Playgroud)

和儿童组件

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>)
              }
            }
Run Code Online (Sandbox Code Playgroud)

但是当我试图阅读父道具时,我有一个错误"TypeError:undefined不是一个对象"
但在我看来,我做的一切都是正确的.

Kar*_*lor 6

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

你正在做的是使用spread运算符传递多个键/值,但如果你的道具是空的,那么什么都不会通过.

<Profile {...this.state} />
Run Code Online (Sandbox Code Playgroud)

是相同的

<Profile
  email={this.state.email}
  first_name={this.state.first_name}
  image={this.state.image}
/>
Run Code Online (Sandbox Code Playgroud)

要将父状态转换为子组件,您需要执行以下操作:

<Profile {...this.state} />
Run Code Online (Sandbox Code Playgroud)

然后在您的子组件中

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