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

时间:2018-09-10 16:37:39

标签: 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>)
      }
    }

和子组件

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:未定义不是对象”
但是在我看来,我所做的一切都正确。

2 个答案:

答案 0 :(得分:5)

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

您正在执行的操作是使用传播运算符传递多个键/值,但是如果您的道具为空,则不会传递任何内容。

<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'

答案 1 :(得分:0)

卡尔提到的关于通过状态的说法是正确的,但是子组件也存在问题。

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

这应该可以解决问题。

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

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

相关问题