如何使用类似于Instagram的功能(如按钮)与本机做出反应

时间:2018-06-03 03:36:56

标签: reactjs react-native

您好我正试图通过更改按下的图像来制作一个类似Instagram的按钮,但是当我按下图像时没有变化

一切都是最新的。代码没有错误。

这是我的代码:

import React, { Component } from 'react';
import { View, Text, StyleSheet, Image,navigation,TouchableOpacity } from 'react-native';
import { Container, Content, Badge, Left, Icon, Header} from 'native-base';
import { DrawerActions } from 'react-navigation';

class HomePage extends Component {
    constructor(props){
        super(props)
        this.state = {
        likedQ: false,   
         uri: require('./images/mianIcons/like.png') 
        }
    }

    _ifLiked = () => {
        likedQ = true;
        uri: require('./images/mianIcons/like3.png') 
    }

    render(){
        return(
               <View>
                    <Header>
                        <Left>
                          <Icon name="ios-menu" onPress={()=> this.props.navigation.openDrawer()}
                          />
                        </Left>
                   </Header>   

                  <TouchableOpacity onPress={this._ifLiked()}>  
                    <Image 
                    style={{width: 32 , height: 32 ,}}
                    source={require(uri)}
                   />
                  </TouchableOpacity>          
           </View>           

        )
    }
}

export default HomePage;

1 个答案:

答案 0 :(得分:0)

您应该设置状态以重新呈现组件

_ifLiked = () => { 
  this.setState({
    likedQ: true, 
    uri: require('./images/mianIcons/like3.png')
  }
} 

像这样改变你的onPress功能。您应该为反应组件设置更新状态

,这是基本的事情

还有一些更正。以下是更正后的代码

class HomePage extends Component{ 
  constructor(props){ 
    super(props) 
    this.state = { 
      likedQ: false, 
      uri: './images/mianIcons/like.png' 
    } 
  } 

  _ifLiked = () => { 
  this.setState({
    likedQ: true, 
    uri: require('./images/mianIcons/like3.png')
  }
}  

  render(){ 
   return( 
    <View> 
      <Header> 
        <Left> 
          <Icon name="ios-menu" onPress={()=> this.props.navigation.openDrawer()} /> 
       </Left> 
     </Header> 
     <TouchableOpacity onPress={() => this._ifLiked}> 
       <Image style={{width: 32 , height: 32}} source={require(this.state.uri)} /> 
     </TouchableOpacity> 
   </View> 
 )} 
}