【发布时间】:2022-01-03 09:31:40
【问题描述】:
在我使用 React.js 的应用程序中的一个功能组件中,调用 getElementsByClassName 会返回“未定义”,显然,有一个带有 className 的部分标记。
import React from 'react';
import Expansion from './Expansion';
// ExpansionView refers to the container box that displays individual expansion boxes
const ExpansionView = (props) => {
const validExpansion = [
"Classic", "Naxxramas", "Goblins vs Gnomes", "Blackrock Mountain", "The Grand Tournament",
"The League of Explorers", "Whispers of the Old Gods", "One Night in Karazhan", "Mean Streets of Gadgetzan",
"Journey to Un'Goro", "Knights of the Frozen Throne", "Kobolds & Catacombs", "The Witchwood",
"The Boomsday Project", "Rastakhan's Rumble", "Rise of Shadows", "Saviors of Uldum", "Descent of Dragons",
"Galakrond's Awakening", "Ashes of Outland", "Scholomance Academy", "Madness At The Darkmoon Faire",
"Forged in the Barrens", "United in Stormwind",
];
// length is 24
//create a function that will filter by validExpansion and create an Expansion component
const expansionGenerator = (props) => {
const expansionViewTag = document.getElementsByClassName('expansionView')[0];
for (let i = 0; i < validExpansion.length; i += 1) {
expansionViewTag.appendChild(
<Expansion key={props.expansion[validExpansion[i]]} selectExpansion={props.selectExpansion}/>
)
}
return
// return <Expansion expansion={props.expansion} selectExpansion={props.selectExpansion}/>
}
return(
<section className='expansionView'>
{expansionGenerator(props)}
</section>
)
}
export default ExpansionView;
循环的2个原因:
- 在return语句中写24次并不理想。(因此要追加)
- 为 each 分配 props,props 将只是数组 validExpansion 中的每个元素。
请帮我提供一个有效的解决方案,谢谢!
【问题讨论】:
标签: reactjs react-functional-component getelementsbyclassname