![](/img/trans.png)
[英]Warning: Unknown prop on <> tag. Remove this prop from the element
[英]ReactJS - Unknown prop `activeClassName` on <a> tag. Remove this prop from the element
我正在使用 react 15.4.2 和 react-router4.0.0 並且這個項目是用Create React App引導的。
這是我的代碼。
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import {BrowserRouter as Router,Route,Link} from 'react-router-dom'
const AboutPage = () => {
return(
<section>
<h2>This is About page</h2>
<Link activeClassName="active" to="/about/nestedone">Nestedone</Link>
{' '}
<Link activeClassName="active" to="/about/nestedtwo">Nested two</Link>
</section>
)
}
const HomePage = () => {
return(
<section>
<h2>This is Home page</h2>
<Link to="/about">About</Link>
</section>
)
}
const NestedOne = () => {
return (
<section>
<h2>Nested page 1</h2>
</section>
)
}
const NestedTwo = () => {
return (
<section>
<h2>Nested page 2</h2>
</section>
)
}
ReactDOM.render(
<Router>
<section>
<Route exact path="/" component={HomePage} />
<Route path="/about" component={AboutPage} />
<Route path="/about/nestedone" component={NestedOne} />
<Route path="/about/nestedtwo" component={NestedTwo} />
</section>
</Router>,
document.getElementById('root')
);
當我瀏覽/about
時,我收到此錯誤:
“警告:標簽上的未知道具
activeClassName
。從元素中刪除此道具。
我在這里做錯了什么?
謝謝!
activeClassName
屬性不是 Link 的屬性,而是 NavLink 的屬性。
因此,只需更改您的代碼以使用 NavLink 而不是 Link:
const AboutPage = () => {
return(
<section>
<h2>This is About page</h2>
<NavLink activeClassName="active" to="/about/nestedone">Nestedone</NavLink>
{' '}
<NavLink activeClassName="active" to="/about/nestedtwo">Nested two</NavLink>
</section>
)
請記住從react-router-dom
導入NavLink
:
import { NavLink } from 'react-router-dom'
從v6開始,react-router 將activeClassName
替換為className
並使用navData.isActive
來切換樣式。
老辦法:
<NavLink to="/home" activeClassName="active-style">Home</NavLink>
v6 及以上版本:
<NavLink to="/home" className={(navData) => (navData.isActive ? "active-style" : 'none')}>Home</NavLink>
或者您也可以從navData
解構isActive
:
<NavLink to="/home" className={({isActive}) => (isActive ? "active-style" : 'none')}>Home</NavLink>
在 React Router v6 中, activeClassName
已更改為className
,其中一個 prop isActive
可用於操作樣式。
const AboutPage = () => {
return(
<section>
<h2>This is About page</h2>
<NavLink className={({ isActive }) => isActive? "active": ''} to="/about/nestedone">Nestedone</NavLink>
{' '}
<NavLink className={({ isActive }) => isActive? "active": ''} to="/about/nestedtwo">Nested two</NavLink>
</section>
)
}
activeClassName
不是Link
的屬性,而是NavLink
的屬性。
從 react-router v4 beta8 開始,該屬性默認active
。 驗證您的節點模塊文件夾中安裝了哪個版本
我的問題是我正在使用reactstrap
並導入他們的NavLink
元素,該元素沒有屬性activeClassName
。 確保從 react-router 庫中導入NavLink
,如下所示:
import { NavLink } from 'react-router-dom'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.