開始學習 React,我正在嘗試將道具傳遞給另一個組件以根據值串列進行渲染,但是在嘗試這樣做時我得到了注意到的錯誤,即使我找不到我的代碼和作業代碼之間的區別。第一個組件:
const navbarCollection = [
{ id: 1, item: 'Home', ref: '#'},
{ id: 2, item: 'Search', ref: '#'},
{ id: 3, item: 'Login', ref: '#'},
{ id: 4, item: 'Register', ref: '#'},
];
function UnorderedListNavBar() {
return (
<div id='wrapper-navBarList'>
<ul className='navbar-nav mr-auto'>
{
navbarCollection.map((menuItem) => {
return (<ListItem key={menuItem.id} mykey={menuItem.item} value={menuItem.ref} />);
})
}
</ul>
</div>
)
}
export default UnorderedListNavBar;
第二部分:
function ListItem(id, type, href) {
return (
<div id='wrapper-navBarListItem'>
<li className='list-item active'>
<a className='nav-link' href={href}>test</a>
</li>
</div>
)
}
export default ListItem;
老實說,我什么都試過了。當我將使用第一個組件發送的內容記錄到第二個組件時,我會得到字串作為結果,但是當從第二個組件記錄(或嘗試使用資料)時,它會顯示一個物件。
請幫助我,我將不勝感激任何幫助,尤其是解釋,以便我學習。非常感謝!
uj5u.com熱心網友回復:
function ListItem({mykey, value}) {
return (
<div id='wrapper-navBarListItem'>
<li className='list-item active'>
<a className='nav-link' href={value}>test</a>
</li>
</div>
)
}
export default ListItem;
您面臨的錯誤是因為您發送給子組件的物件與您在子組件中收到的不同
uj5u.com熱心網友回復:
你需要以這種方式解構你的道具
function ListItem({ id, mykey, href }) {
return (
<div id="wrapper-navBarListItem">
<li className="list-item active">
<a className="nav-link" href={href}>
test {mykey}
</a>
</li>
</div>
);
}
uj5u.com熱心網友回復:
//A more compact way to pass your props
const navbarCollection = [
{ id: 1, item: 'Home', ref: '#'},
{ id: 2, item: 'Search', ref: '#'},
{ id: 3, item: 'Login', ref: '#'},
{ id: 4, item: 'Register', ref: '#'},
];
function UnorderedListNavBar() {
return (
<div id='wrapper-navBarList'>
<ul className='navbar-nav mr-auto'>
{
navbarCollection.map((menuItem) => {
const {id, item, ref} = menuItem;
return <ListItem key={id} {...{id, item, href: ref}} />
})
}
</ul>
</div>
)
}
export default UnorderedListNavBar;
而 ListItem 組件是,
function ListItem(props) {
const {id, type, href} = props
return (
<div id='wrapper-navBarListItem'>
<li className='list-item active'>
<a className='nav-link' href={href}>test</a>
</li>
</div>
)
}
export default ListItem;
uj5u.com熱心網友回復:
你可以有
function ListItem(props) {
return (
<div id='wrapper-navBarListItem'>
<li className='list-item active'>
<a className='nav-link' href={props.href}>{props.item}</a>
</li>
</div>
)
}
或者
function ListItem({href, item}) {
return (
<div id='wrapper-navBarListItem'>
<li className='list-item active'>
<a className='nav-link' href={href}>{item}</a>
</li>
</div>
)
}
我們有這個組件收到的道具。我們可以通過props.href、props.item等呼叫接收到的組件的屬性,但是有“props”就麻煩了。每次,所以我們使用 {} 來破壞道具,然后我們可以使用 href, item 來呼叫屬性。
對于上述任何組件,請像這樣呼叫它:
<ListItem key={menuItem.id} item={menuItem.item} href={menuItem.ref} />
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/494254.html
標籤:javascript 反应
上一篇:將包含嵌套物件、字串、陣列的節點轉換為無序串列(Javascript)
下一篇:將陣列推入TS中的陣列陣列
