javascript - 通过 React Native 更改图标 activeIndex
问题描述
如何通过 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>
);
}
}
解决方案
编写时正在调用该函数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
});
}
推荐阅读
- python - 使用 numpy 逐行连接不同大小的数组
- vue.js - Nuxt.js:客户端在生产中失败,但在开发期间工作
- python - Pytest-django:测试后无法删除数据库
- javascript - 用没有css的js改变html元素的位置
- android - 寻找避免在共享首选项中覆盖键值的最佳方法
- nlp - Doc2Vec vs Avg Word Vectors:哪个更适合情感分析?
- java - 使用正则表达式从字符串中提取数据
- ios - 将 UIPickerView 放在 UIAlertController 的中心
- android - 我的 recyclerview 适配器只是加载第一个视图,
- android - 从样式加载这些属性时,一个或多个布局缺少布局高度和布局宽度错误