代码之家  ›  专栏  ›  技术社区  ›  Saeed Heidarizarei

通过react native更改图标activeindex

  •  2
  • Saeed Heidarizarei  · 技术社区  · 8 年前

    如何通过react native更改图标activeindex? 我在用 native-base 模块,但不工作 activeIndex == 0 是活动的,我的功能不起作用。

    代码:

    import {Icon, Button} from 'native-base';
    type Props = {};
    export default class App extends Component<Props> {
      constructor(props) {
    
        super(props);
        this.segmentClicked = this.segmentClicked.bind(this);
        this.state = {
          activeIndex: 0
        }
      }
    
      segmentClicked = (index) => {
        this.setState = ({
          activeIndex: index
        })
      }
      render() {
        return (
          <View style={styles.container}>
            <View style={{flexDirection: 'row', justifyContent: 'space-around', borderTopWidth: 1, borderTopColor: '#eae5e5'}}>
              <Button
                onPress={this.segmentClicked(0)}
                active={this.state.activeIndex == 0}
              >
                <Icon name='ios-apps-outline'
                  style={[this.state.activeIndex == 0 ? {} : {color: 'gray'}]}
                />
              </Button>
              <Button
                onPress={this.segmentClicked(1)}
                active={this.state.activeIndex == 1}
              >
                <Icon name='ios-list-outline'
                  style={[this.state.activeIndex == 1 ? {} : {color: 'gray'}]}
                />
              </Button>
              <Button
                onPress={this.segmentClicked(2)}
                active={this.state.activeIndex == 2}
              >
                <Icon name='ios-people-outline'
                  style={[this.state.activeIndex == 2 ? {} : {color: 'gray'}]}
                />
              </Button>
              <Button
                onPress={this.segmentClicked(3)}
                active={this.state.activeIndex == 3}
              >
                <Icon name='ios-bookmark-outline'
                  style={[this.state.activeIndex == 3 ? {} : {color: 'gray'}]}
                />
              </Button>
            </View>
          </View>
        );
      }
    }
    
    1 回复  |  直到 8 年前
        1
  •  1
  •   Tholle    8 年前

    你在写的时候调用函数 this.segmentClicked(1) 是的。相反,你想给一个函数 Button 被按下。

    例如,可以创建一个新的内联箭头函数。

    <Button
      onPress={() => this.segmentClicked(1)}
      active={this.state.activeIndex == 1}
    >
      <Icon name='ios-list-outline'
        style={[this.state.activeIndex == 1 ? {} : {color: 'gray'}]}
      />
    </Button>
    

    你还得打电话给 setState 函数,不为其分配新值。

    segmentClicked = (index) => {
      this.setState({
        activeIndex: index
      });
    }
    
    推荐文章