如何在单击onPress按钮后更改按钮上的图标(图标名称属性)

问题描述 投票:0回答:2

我有Button组件,上面有文字和图标。本机库中的按钮和图标...如何在单击按钮后更改图标(图标名称属性)

代码片段:

<Button
    onPress={}
    transparent
    iconRight
    small   
 >
  <Text style={{ color: 'red', fontSize: 18 }}>HIDE</Text>
   <Icon
     name='ios-arrow-down-outline'
     style={{ color: 'red', fontSize: 18 }} 
    />
   </Button>
react-native native-base
2个回答
2
投票

您可以通过按下按钮后更改状态来实现此目的:

工作演示:https://snack.expo.io/r1dHpDBvX

示例代码:

import React, { Component } from 'react';
import { Container, Header, Content, Button, Text, Icon } from 'native-base';

export default class ButtonThemeExample extends Component {
  constructor() {
   super();
   this.state = { iconName: "md-arrow-back" };
  }

  render() {
    return (
     <Container>
       <Header />
         <Content>
           <Button
             onPress={ () => this.setState(
               { iconName: "md-arrow-down" }
             )}
             transparent
             iconRight
             small   
            >
            <Text style={{ color: 'red', fontSize: 18 }}>HIDE</Text>
            <Icon
              name= {this.state.iconName}
              style={{ color: 'red', fontSize: 18 }} 
            />
          </Button>
        </Content>
      </Container>
     );
    }
  }

希望这个有效!


0
投票

你可以试试这个:

        const defaultImage = require('../images/defaultImage.png');
        const changedImage = require('../images/changedImage.png');   
        class ChangeImage extends Component {
          constructor() {
            super();
            this.state = { showDefaultImage: true };
          }

          renderImage() = {
           const imgSrc = this.state.showDefaultImage? defaultImage : changedImage;
            return (
              <Image
                source={ imgSrc }
              />
            );
          }
          render(){
            return (
              <View>
                  <TouchableOpacity
                   onPress={ () => this.setState(
                   { showDefaultImage: !this.state.showDefaultImage }
                )} 
                  />
                    {this.renderImage()}
                  </TouchableOpacity>
                </View>
            );
          }
        }

希望这会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.