gpt4 book ai didi

reactjs - 构建下拉组件

转载 作者:行者123 更新时间:2023-12-02 16:59:55 26 4
gpt4 key购买 nike

我在构建下拉组件时遇到问题。在获取所选项目的函数中,我遇到此错误:

Too many re-renders. React limits the number of renders to prevent an infinite loop.

组件的代码:

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;

最佳答案

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

您在每次渲染时调用此函数,并且它会在每次渲染时修改状态,因此会再次递归调用。

您可以通过以下方式解决:

<div className="dropdown-popup-row" 
key={item.id}
onClick={() => Changed(item)}>
{item.value}
</div>

关于reactjs - 构建下拉组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59487322/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com