Building Dropdown component

问题描述 投票:1回答:1

我在构建dropdown component时遇到问题。在获取所选项目的函数中,出现此错误:

重新渲染过多。 React限制renders的数量以防止无限循环。

组件的代码:

import React, { useState } from 'react';
import PropTypes from 'prop-types';

import '../../../App.css'

function Dropdown({ items }) {

    //const [list, setList] = useState(items);

    const [selectedItem, setSelectedItem] = useState(items[0]);
    const [showItems, setShowItem] = useState(false);
    const [setExpand, setExpandState] = useState("");


    function toggleDropdown() {
        setExpandState(setExpand === "" ? "dropdown-expanded dropdown-expanded-down" : "");
        setShowItem(showItems === false ? true : false);
    };

    const Changed = (item) => {

        setShowItem(false);
        setSelectedItem(item);

    }


    return (

        <div data-dropdown="" className={`dropdown-container dropdown ${setExpand}`} onClick={toggleDropdown} >
            <div className="dropdown-display">
                <div className="dropdown-display-content" >
                    <span data-expression="" class="OSFillParent"> {selectedItem.value}  </span>
                </div>
            </div>
            <div className="dropdown-list" style={{ display: showItems ? 'block' : 'none' }}  >
                <div className="scrollable-list scrollable-list-with-scroll">
                    {items.map(item =>
                        <div className="dropdown-popup-row" key={item.id} onClick={Changed(item)} > {item.value} </div>
                    )}
                </div>
            </div>

        </div>

    );


}

Dropdown.propTypes = {
    items: PropTypes.array,

}

export default Dropdown;
reactjs drop-down-menu components
1个回答
4
投票

问题在这里onClick={Changed(item)}

您在每个渲染器上都调用此方法,并且它正在修改每个渲染器的状态,因此将以递归方式再次调用它。

您可以通过执行以下操作来解决它:

<div className="dropdown-popup-row" 
  key={item.id} 
  onClick={() => Changed(item)}> 
  {item.value} 
</div>
© www.soinside.com 2019 - 2024. All rights reserved.