使用React,如何仅在单击按钮时创建文本字段,并在单击按钮后继续创建更多文本字段


const [showNotes, setShowNotes] = useState(false);
const generateNotes = () => {
setShowNotes(true);
<TextField id="notesField" label="Add your note here" variant="outlined"/>
};
<div style = {{ display: 'flex', width: '300px', justifyContent: 'space-between' }}>

<Button id="note" onClick={generateNotes} variant="contained" component="label" style = {{ backgroundColor: '#3f78b5', flex: '50px', width: '122px', height: '38px', 
borderRadius: '8px', left: '388px', position: 'absolute' }}>
Add Note
</Button>
</div>

我创建了一个useState变量,并将其初始化为false。然后,我创建了一个函数,将其设置为true并创建文本字段。然后,当点击按钮时,它应该会显示文本字段,但这并没有发生。我意识到我没有在任何地方设置showNotes变量,但我不确定该设置什么。

您可以通过一个数组来实现这一点,按钮会将一些文本附加到该数组中,react会为每个项目创建一个TextField组件,例如:

const [notes, setNotes] = useState([]);
const generateNotes = () => {
notes.push('some label');
setNotes([ ...notes ]);
};
return (
<div>

<Button id="note" onClick={generateNotes}></Button>
{
notes.map((item, index)=>{
return <TextField key={index} label={item)/>
}
}
</div>
)

不能在回调中呈现TextField,它应该来自组件返回。您可以创建一个计数器来增加输入字段的数量,并且只有当计数大于零时才进行渲染。

const [inputFieldCount, setInputFieldCount] = useState(0);
const generateNotes = () => {
setInputFieldCount((count) => count + 1);
};
return (
<div
style={{ display: "flex", width: "300px", justifyContent: "space-between" }}
>
<Button onClick={generateNotes}>Add Note</Button>
{inputFieldCount > 0 && Array.from({ length: inputFieldCount }, (_, index) => (
<TextField
key={index}
id="notesField"
label="Add your note here"
variant="outlined"
/>
))}
</div>
);

Array.from的第二个参数是用于迭代数组计数的映射函数。

最新更新