React-strap组件重命名致重复声明错误,求原因解析
问题原因与解决办法
这个错误的根源很明确:你自定义的Nav组件和react-strap内置的Nav组件重名了。
当你在项目里引入react-strap的组件(比如写了import { Nav } from 'react-strap'),同时又在你的nav.component.jsx里声明了一个名为Nav的默认导出类时,同一个作用域里就出现了两个同名的标识符,模块构建工具自然会抛出"Duplicate declaration 'Nav'"的错误——它不知道你指的是哪个Nav。
两种可行的解决方式
1. 给自定义组件换个独特的名字
这是最直接的方案,给你的导航组件起个不会和第三方库撞名的名字,比如AppNav、CustomNavbar之类的:
// in bsp/nav.component.jsx export default class AppNav extends React.Component { constructor(props) { super(props); this.toggle = this.toggle.bind(this); this.state = { isOpen: false }; } // ... 你的其他组件逻辑 }
2. 给react-strap的Nav组件取别名
如果你特别想用Nav作为自定义组件的名字,可以在导入react-strap的组件时给它加个别名,这样就能区分开两个Nav了:
// 导入时给react-strap的Nav起别名 import { Nav as StrapNav } from 'react-strap'; // 继续使用Nav作为自定义组件名 export default class Nav extends React.Component { constructor(props) { super(props); this.toggle = this.toggle.bind(this); this.state = { isOpen: false }; } render() { // 使用别名StrapNav来调用react-strap的内置组件 return ( <StrapNav className="navbar"> {/* 你的导航内容 */} </StrapNav> ); } }
这样就能彻底解决标识符冲突的问题,模块构建也能正常通过了。
内容的提问来源于stack exchange,提问作者Thomas James Thorstensson
相关产品推荐
相关产品推荐

