简体   繁体   English

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

[英]Using React, how do I create a textfield only when a button is clicked and keep on creating more textfields when the button is clicked?

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>

I created a useState variable and initialized it to false.我创建了一个 useState 变量并将其初始化为 false。 Then, I created a function that would set it to true and create the textfield.然后,我创建了一个 function 将其设置为 true 并创建文本字段。 Then when the button is clicked it should display the textfield but that is not happening.然后,当单击按钮时,它应该显示文本字段,但这并没有发生。 I realize I did not set the showNotes variable anywhere but I am not sure on what to set to that.我意识到我没有在任何地方设置 showNotes 变量,但我不确定要设置什么。

you can do this by having an array that the button appends some text to, and react will create a TextField component for every item, example:您可以通过让按钮附加一些文本的数组来做到这一点,并且 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>
)

You cannnot render TextField inside a callback, it should be from your component return.You can create a counter to increment the number of input fields and render only if count is greater than zero.您不能在回调中呈现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>
);

The second argument from Array.from is a map function to iterate over the array count. Array.from的第二个参数是 map function 以迭代数组计数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM