[英]Make a separate conditional rendering inside for loop react js
const [isAgent, setAgent] = useState(true);
{isSupervisor.map((value, index) => {
return <div className="text-gray-700 rounded-lg" key={index}>
{isAgent ? <div className="flex flex-row">
<div className=" flex-none text-center">
<div>Halo</div>
</div>
<div className="flex-grow text-gray-700 px-2 py-1 my-auto">
<button onClick={() => setAgent(true)} className="bg-custom-14 ">Edit</button>
</div>
</div>
</div>
</div> : <div>
<div className="flex flex-col my-2 mx-8">
<div className=" flex-none text-center">
<div>Halo</div>
</div>
<div className="flex justify-end">
<button onClick={() => setAgent(false)} className="bg-custom-14">Discard</button>
</div>
</div> </div>
問題:當我單擊條件按鈕時,所有按鈕都遵循條件,是否有任何解決方案可以在每個按鈕中單獨設置條件? 謝謝
我寫這個答案是假設在這個帶有按鈕的部分列表中,您只需要在單擊“編輯”時更改一個部分。 Since isAgent
and setAgent
affect all sections at once, your state should have a map of states for each sections, isAgent
should be a function to retrieve balue from this state by a section key, and setAgent
should accept the section key. 因此,您的反應 state 可能看起來像這樣:
class State {
editingAgents = {};
isAgent = (index) => editingAgents[index];
setAgents = (index, isAgent) => editingAgents[index] = isAgent;
}
並且修改后的組件代碼可能是這樣的(注意現在isAgent
和setAgent
是如何使用的)
const [isAgent, setAgent] = useState(true);
{isSupervisor.map((value, index) => {
return <div className="text-gray-700 hover:bg-custom-8 rounded-lg" key={index}>
{isAgent(index) ? <div className="flex flex-row">
<div className=" flex-none text-center mx-2 my-1">
<img src={Ane} className=" w-54px lg:w-50px object-contain"></img>
</div>
<div className="flex-grow text-gray-700 px-2 py-1 my-auto">
<button onClick={() => setAgent(index, true)} className="bg-custom-14 ">Edit</button>
</div>
</div>
</div>
</div> : <form onSubmit={handleSubmit(updateAgent)}>
<div className="flex flex-col my-2 mx-8">
<div className="m-2 lg:mt-4 hidden">
<div className="inline-block w-3/12 text-base lg:text-sm font-semibold">Id</div>
</div>
<div className="flex justify-end">
<button onClick={() => setAgent(index, false)} className="bg-custom-14">Discard</button>
</div>
</div> </form>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.