[英]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>
problem: when i click a condition button, all button follow the condition, is there any solution to make a separate condition in every button?问题:当我单击条件按钮时,所有按钮都遵循条件,是否有任何解决方案可以在每个按钮中单独设置条件? thanks
谢谢
I write this answer assuming that in this list of sections with buttons you only need to change one section on clicking 'edit'.我写这个答案是假设在这个带有按钮的部分列表中,您只需要在单击“编辑”时更改一个部分。 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. 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. So, your react state may look ike this:因此,您的反应 state 可能看起来像这样:
class State {
editingAgents = {};
isAgent = (index) => editingAgents[index];
setAgents = (index, isAgent) => editingAgents[index] = isAgent;
}
and modified component code may be like this (notice how isAgent
and setAgent
are used now)并且修改后的组件代码可能是这样的(注意现在
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.