React native 渲染函数中未定义状态属性
在其中一个视图的渲染函数中,我试图将视图的不透明度绑定到状态属性:this.state.infoOpacity 这是一个错误“undefined不是对象(计算'This.state.infoOpacity')” 任何指导都会有帮助React native 渲染函数中未定义状态属性,react-native,React Native,在其中一个视图的渲染函数中,我试图将视图的不透明度绑定到状态属性:this.state.infoOpacity 这是一个错误“undefined不是对象(计算'This.state.infoOpacity')” 任何指导都会有帮助 export default class BookView extends Component { constructor(props) { super(props); this.state = { hideInfo:false,
export default class BookView extends Component
{
constructor(props) {
super(props);
this.state = {
hideInfo:false,
infoOpacity:0.80,
swiperWidth:Dimensions.get('window').width,
swiperHeight:Dimensions.get('window').height
};
}
render() {
pages.forEach(function(ranPage){
photoViews.push(
<View key={ranPage.letter} style={{width: Dimensions.get('window').width, height: Dimensions.get('window').height}}>
<View style={[styles.meow,{opacity: this.state.infoOpacity}]}>
<Text style={styles.text}>{ranPage.name}</Text>
<Text style={styles.text}>{ranPage.phonetic}</Text>
<Text style={styles.text2}>{ranPage.description}</Text>
</View>
</View>
)
});
return (
<View style={{flex:1}}>
<Swiper showsButtons={false} style={{backgroundColor:'#000'}} width={this.state.swiperWidth} height={this.state.swiperHeight}>
{photoViews}
</Swiper>
</View>
);
}
}
导出默认类BookView扩展组件
{
建造师(道具){
超级(道具);
此.state={
hideInfo:错,
信息不透明度:0.80,
swiperWidth:Dimensions.get('window').width,
swiperHeight:Dimensions.get('window').height
};
}
render(){
pages.forEach(函数(ranPage){
推(
{ranPage.name}
{ranPage.拼音}
{ranPage.description}
)
});
返回(
{photoViews}
);
}
}
forEach函数中的上下文已更改。使用箭头功能解决您的问题。所以不是
pages.forEach(函数(ranPage){…})代码>
写这个
pages.forEach((ranPage)=>{…})代码>就是这样!非常感谢。你知道关于react native context的任何好的阅读资料吗?我可以这样做,这样我就不会再犯这个错误了。它实际上与react native本身无关,而是与javascript有关。只要一直使用箭头函数,现在几乎总是正确的选择:)您还可以使用臭名昭著的bind
函数来避免失去上下文。那么您的forEach
函数应该看起来像pages.forEach(函数(ranPage){photoViews.push(…这里有一些JSX…)}.bind(this))代码>但是,使用arrow函数是更好的修复方法。