我的 App.js 中有导航屏幕,其中一个屏幕将自定义 header 呈现为:
const DailyStack = createStackNavigator({
Dashboard,
SalesDashboard: {
screen : SalesDashboard,
navigationOptions:{
header: null,
}
},
StackNavSecond : {
screen: StackNavSecond,
navigationOptions : {
header : <CustomHeader />,
}
},....
然后在我的 CustomHeader.js
文件中,我有一些状态数据:
class CustomHeader extends Component {
constructor(props) {
super(props)
this.state = {
title:'Regions',
subtitle:'',
oem: ''
}
}
async componentDidMount(){
let car_brand = await AsyncStorage.getItem('brand_name');
let main_oem = await AsyncStorage.getItem('oem_name');
await this.setState({
oem: main_oem,
subtitle: car_brand,
});
console.log(this.state.oem)
}
render() {
console.log(this.state.title)
const {title, subtitle, oem} = this.state;
return (
<View>
<CustomDropdown title={title} subtitle={subtitle} oem={oem} />
</View>
)
}
}
export default withNavigation(CustomHeader);
prop title
没有传递给它的子组件,它在另外两个屏幕中进一步呈现。
CustomDropdown.js
的代码是:
class CustomDropdown extends Component {
constructor(props) {
super(props)
this.state = {
title: '',
oem: '',
subtitle:''
};
}
componentDidMount(){
this.setState({
title:this.props.title,
subtitle: this.props.subtitle,
oem: this.props.oem,
});
console.log(this.state.title, this.state.oem, this.state.subtitle)
}
render() {
return (
<View style={{flexDirection:'row', justifyContent: 'space-between'}}>
.........
</View>
)
}
}
export default withNavigation(CustomDropdown);
当我控制 this.state.title
时,它打印但没有 subtitle
和 oem
的值。我什至尝试将控制台语句放在 this.setState()
的 callback()
中,但仍然没有打印 oem 和字幕的 Prop 。
请帮助解决这个问题。
最佳答案
当您不想交付组件时,您可以使用 withNavigation
。但是您的代码嵌套很深。
如果你想这样使用它,你可以像这样更改代码。
CustomHeader.js
class CustomHeader extends React.Component {
constructor(props) {
super(props)
this.state = {
title:'Regions',
subtitle:'',
oem: ''
}
}
async componentDidMount(){
let car_brand = await AsyncStorage.getItem('brand_name');
let main_oem = await AsyncStorage.getItem('oem_name');
this.setState({
oem: main_oem,
subtitle: car_brand,
});
console.log(this.state.oem)
}
render() {
console.log(this.state.title)
const {title, subtitle, oem} = this.state;
return (
<View>
<CustomDropdown title={title} subtitle={subtitle} oem={oem} />
</View>
)
}
}
export default withNavigation(CustomHeader);
CustomDropdown.js
class CustomDropdown extends React.Component {
constructor(props) {
super(props);
this.state = {
title: props.title,
oem: props.oem,
subtitle: props.subtitle
};
}
componentDidMount(){
console.log(this.state.title, this.state.oem, this.state.subtitle)
}
render() {
return (
<View style={{flexDirection:'row', justifyContent: 'space-between'}}>
.........
</View>
)
}
}
export default CustomDropdown;
关于javascript - 无法将 Prop 从父组件传递到子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57574076/