为什么 getElementsByClassName 在 React 的功能组件中返回 undefined?

Why is getElementsByClassName returning undefined in React's functional component?

在我使用 React.js 的应用程序中的一个功能组件中,调用 getElementsByClassName returns 'undefined',很明显,有一个带有 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 个原因:

  1. 在return语句中写24次不理想。(因此想追加)
  2. 为每个分配道具,道具将只是数组 validExpansion 中的每个元素。

请帮我提供一个有效的解决方案,谢谢!

因为当您最初进行渲染并且 React 尚未向 DOM 提交任何内容时,className='expansionView' 类名还不存在于 document 中。

在 React 中,直接操作 DOM 是一种反模式,例如通过 id/class/etc 获取元素并将子节点附加到它。

如果您想遍历数组结构并呈现 JSX,则使用映射函数迭代数组并将每个元素映射到某个 JSX。

const ExpansionView = ({ expansion, selectExpansion }) => {
  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",
  ];

  return (
    <section className='expansionView'>
      {validExpansion.map(value => (
        <Expansion key={expansion[value]} selectExpansion={selectExpansion}/>
      ))}   
    </section>
  );
};