React-Router 使用经验 之 根据当前地址选中tabbar

308 阅读1分钟

根据当前地址选中tabbar

  • 直接使用props 中提供的 location 属性

    为什么不使用 history 中的location呢,因为history中的location变化时,不会触发 组件更新(出现这种情况的原因在于:react决定是否更新是根据浅层对比数据是否发生变化, 所以 props.location 变化就可以触发更新,props.history.location 变化就不会触发更新)

        {/* 底部导航 start */}
        <div className="tabbar" >
          <TabBar barTintColor="#fff" unselectedTintColor="#9b9b9b" tintColor="#75bea1" tabBarPosition="bottom" hidden={this.state.hiddenTabbar}>
            {this.state.tabbarList.map(val => (
              // 导航项
              <TabBar.Item
                key={val.path}
                title={val.title}
                // 如果当前路由中含有 对应path则选中
                selected={this.props.location.pathname.includes(val.path)}
                // 点击跳转对应路由
                onPress={() => { this.props.history.push(val.path) }}
                icon={<i className={"iconfont " + val.iconName}></i>}
                selectedIcon={<i className={"iconfont " + val.iconName}></i>}
              />
            ))}
          </TabBar>