如何通过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>
);
}
}
答案 0 :(得分:1)
您在编写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
});
}