Change Icon activeIndex via React Native

问题: How to Change Icon activeIndex via React Native? I'm using native-base module, but not work and just activeIndex == 0 is active and my function not work. Code: import {...

问题:

How to Change Icon activeIndex via React Native? I'm using native-base module, but not work and just activeIndex == 0 is active and my function not work.

Code:

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:

You are calling the function when you write this.segmentClicked(1). Instead you want to give a function that will be called when the Button is pressed.

You can e.g. create a new inlined arrow function.

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

You also have to call the setState function, not assign a new value to it.

segmentClicked = (index) => {
  this.setState({
    activeIndex: index
  });
}
  • 发表于 2018-07-05 15:30
  • 阅读 ( 296 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除