繁体   English   中英

使用状态错误反应本机更改 img

[英]React native changing img with state Error

首先对不起大家,因为我的英语水平很低。

我正在学习本机反应。 尝试使用状态更改图像但不起作用。 错误:null 不是对象 (this.state.admob)

索引.js


   class HomeScreen extends React.Component {    
   constructor(props){
       super(props);
       this.state = {admob: require('../Img/admob1.jpg'), admobCount: 0};
   }

   _changeAdmob(){
       this.setState({
           if(admobCount = 0){
               admobCount: this.state.admobCount + 1;
               admob: require('../Img/admob1.jpg');
           },
           if(admobCount = 1){
               admobCount: 0;
               admob: require('../Img/admob2.png');
           }
       });
   }

   componentDidMount(){
       this.admobTimer = setInterval(
           () => this._changeAdmob(), 2000
       );
   }

   componentWillUnmount(){
       clearInterval(this.admobTimer);
   }

   render() {                          
     return (          
         <View style={styles.MasterContainer}>
             <NavBar navigation = {this.props.navigation}/>
             <UserBar navigation = {this.props.navigation}/>
             <View style={{height: 40,}}></View>
             <ButtonTab/>
             <Admob/>
             <TapBar/>
         </View>
     );
   }
  }

   class Admob extends React.Component{
     render() {
         return(
             <View style={{ flex: 1,alignItems: 'center',justifyContent:'center' }}>
                 <Image style={{ width: 350, height: 70 }} source={this.state.admob}></Image>                 
             </View>
         );
     }
  }

** 我想每 2 秒更改一次图像。**

您需要在组件上传递状态<Admob admob={this.state.admob} />

index.js上添加这个

<View style={styles.MasterContainer}>
          <NavBar navigation = {this.props.navigation}/>
          <UserBar navigation = {this.props.navigation}/>
          <View style={{height: 40,}}></View>
          <ButtonTab/>
          <Admob admob={this.state.admob}/>
          <TapBar/>
</View>

Admob.js 将 this.state 更改为 this.props

<Image style={{ width: 350, height: 70 }} source={this.props.admob}></Image>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM