我们正在使用React.js进行项目。我正在使用react-router-dom配置多个页面,并且我想使用NavLink更改当前活动的图标。icon + sel用于活动页面。我已经根据先前问题的答案重写了代码。SetState也退出了渲染,我稍微触摸了其他设置。import React from 'react';import { Link, NavLink, Router } from 'react-router-dom';import ReactDOM from 'react-dom';import home from './home.svg';import homesel from './homesel.svg';import search from './search.svg';import searchsel from './searchsel.svg';import setting from './setting.svg';import settingsel from './settingsel.svg';import add from './add.svg';import addsel from './addsel.svg';import account from './account.svg';import accountsel from './accountsel.svg';import './Bottom.css';class Bottom extends React.Component { state = { iconName : 'initialIconName' } setIconName = (name) => { this.setState(() => ({ iconName: name })) } oddEvent = (match, location) => { if (!match) return false console.log(location.pathname.substr(1).split('/')[0]) this.setState(() => ({ iconName: location.pathname.substr(1).split('/')[0] })) } render() { return ( <fragment> <div className="bottom noright"> <div className="bottomcontents"> <div className="bottomicon"> <NavLink className="bottomiconinside bottomiconinsideside" src={home} exact to="/" isActive={this.oddEvent}> <img className="iconcenter" src={require(`./home${this.state.iconName == 'home' ? 'sel' : ''}.svg`)}/> </NavLink> <NavLink className="bottomiconinside bottomiconinsideside" exact to="/search" isActive={this.oddEvent}> <img className="iconcenter" src={require(`./search${this.state.iconName == 'search' ? 'sel' : ''}.svg`)}/> } }
1 回答
繁花如伊
TA贡献2012条经验 获得超12个赞
您正在从oddEvent内部调用setState()(屏幕截图显示了它)。您不能通过render()来执行此操作,这会导致重新渲染,然后调用oddEvent,后者会调用setState(),后者导致重新渲染,并且不停地进行。
您将不得不重新考虑您的设计。
添加回答
举报
0/150
提交
取消