【问题标题】:Why is getElementsByClassName returning undefined in React funcitonal component?为什么 getElementsByClassName 在 React 功能组件中返回未定义?
【发布时间】:2022-01-03 09:07:47
【问题描述】:

在我使用 React.js 的应用程序中的一个功能组件中,调用 getElementsByClassName 会返回“未定义”,显然,有一个带有 className 的部分标记。

const ExpansionView = (props) => {

const validExpansion = [
    "Classic", "Naxxramas", "Goblins vs Gnomes",
];

//create a function that will filter by validExpansion and create an Expansion component
const expansionGenerator = (props) => {
    **// the line below returns undefined!**
    const expansionViewTag = document.getElementsByClassName('expansionView')[0];

    for (let i = 0; i < validExpansion.length; i += 1) {
        expansionViewTag.appendChild(
            <Expansion specificExpansion={props.expansion[validExpansion[i]]} selectExpansion={props.selectExpansion}/>
        )
    }
    return 
}

return(
    // clearly, here is a section tag with the className.
    <section className='expansionView'>
       {expansionGenerator(props)}
    </section>
)

}

导出默认ExpansionView;

请看一看。谢谢

【问题讨论】:

    标签: react-functional-component getelementsbyclassname


    【解决方案1】:

    这将在组件安装时呈现undefined,但是如果您重新呈现组件,那么它将返回您期望的结果,因为在初始加载时,您的函数在 react 将 expansionView 附加到 DOM 之前执行。您还可以在渲染后使用 refs 或 useEffect 获取 dom,但在您的情况下不太有用。 对于您的问题,您可以简单地使用 react 组件来呈现您的过滤器组件。

     const App = () => {
    
       const ExpansionComponent = () => {
         // props is shared between App and ExpansionComponent because of closure
         // Do you filters
         return <FilteredComponents /> // example
    
       }  
    
       return (
         <div className="your-class"> 
           <ExpansionComponent />
        </div>
       )
    
     }
    
    

    【讨论】:

      猜你喜欢
      • 2022-01-03
      • 1970-01-01
      • 2017-10-24
      • 2019-12-20
      • 1970-01-01
      • 2019-08-29
      • 2013-07-18
      • 2022-11-12
      • 1970-01-01
      相关资源
      最近更新 更多