我正在处理一个表单,当我单击按钮时,我想添加一个新组件,它只是屏幕上的输入。一切都按计划进行。问题出在以下方面:布局是我有一个主要组件,然后显示了一个子组件。从useState的映射中调用该子组件。 (代码段后的更多内容)
这是主要组件的代码:
import React, { useState } from "react";
import SingleProfile from "./individual_profile";
const ProfileInformation = (props) => {
console.log("proflie render");
const [ProfilesBoolean, setProfilesBoolean] = useState(false);
const [profiles, setProfiles] = useState(props.Data['profiles'])
const FieldAdd = (event)=>{
event.preventDefault();
const copy = profiles;
copy.push({Network:'',url:''})
return(copy)
}
function CreateInput(){
return profiles.map((data, index) =><SingleProfile index={index} data={data} />)
}
const accordion = (event) => {
const NextElement = event.target.nextElementSibling;
if (!event.target.className.includes("display")) {
NextElement.style.maxHeight = NextElement.scrollHeight + "px";
} else {
NextElement.style.maxHeight = 0;
}
};
return (
<div className="AccordionItem">
<div
className={
ProfilesBoolean ? "AccordionHeader-display" : "AccordionHeader"
}
onClick={(e) => setProfilesBoolean(!ProfilesBoolean)}
id="ProfileForm"
>
Profiles
</div>
<div className="AccordionContent">
<div className="AccordionBody">
{
profiles.map((data, index) => (
<SingleProfile index={index} data={data} />
))
}
<button id="ProfileAdd" onClick={(e) => {setProfiles(FieldAdd(e))}}>
Add a profile
</button>
</div>
</div>
</div>
);
};
export default ProfileInformation;
当我单击按钮并且onClick触发FieldAdd()
时,useState更新,并且新的空对象符合预期。但是,它没有出现在我的<div className="AccordionBody">
内部,没有我期望的那样。
以下代码用于通过打开和关闭子div来显示组件。当它打开时,您将看到子组件和添加按钮。如果单击div,将其关闭,然后再次单击以将其重新打开,则会出现新的子组件。
<div
className={ProfilesBoolean ? "AccordionHeader-display" : "AccordionHeader"}
onClick={(e) => setProfilesBoolean(!ProfilesBoolean)}
id="ProfileForm"
>
Profiles
</div>;
是否可以使子组件出现而不必关闭并重新打开div?
答案 0 :(得分:1)
您的clickHandler FieldAdd
不正确。您正在直接更改状态,这不会导致重新渲染。
使用setProfiles
更新clickHandler中的状态。像这样
const FieldAdd = (event)=>{
setProfiles(prev => [...prev, {Network:'',url:''}])
}
像这样触发onClick
<button id="ProfileAdd" onClick={(e) => {FieldAdd(e)}}>
Add a profile
</button>
...