我有一个家长班
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 protected]",
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不是一个对象” 但在我看来,我做的一切都是正确的。
您没有正确地将道具传递给子组件。
你正在做的是使用spread运算符传递多个键/值,但如果你的道具是空的,那么什么都不会通过。
<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 protected]"
// first_name: "User"
// image : '../img/user.png'
Karl提到的关于传递状态的内容是正确的,但是在子组件中也存在问题。
在您的子组件中 - 将this.props.state.xxxx替换为this.props.xxxx,其中xxxx是您的email / first_name / image。
这应该可以解决问题。
(可选建议:如果您想要更简单 - 使用父道具映射您的子状态,以便您可以根据需要更改并提供父项)
这是一个代码沙箱供参考:https://codesandbox.io/embed/9o4vqy4104?module=%2Fsrc%2FuserBlock.js