簡體   English   中英

如何使用 React 在按鈕單擊時添加新的 div

[英]How to add a new div on button click with React

我正在嘗試在我的一個 React 組件中單擊按鈕時添加一個新輸入。 最優雅的方法是什么?

這是我的代碼的抽象:

const addDivs = (type) => { ??? }

export default function Form() {

handleSubmit(e) {...}

return ( 
<form onSubmit={handleSubmit}>
<div><textarea rows="4" placeholder="Write about something here..." /></div>
//New divs should go here

//Adds a textarea
<button onClick={() => addDivs(textarea)}>Add textarea</button>
//Adds an upload field
<button onClick={() => addDivs(upload)}>Add image</button>
<input type="submit" value="Submit" /> </form> ); 
}

我想將按鈕保留在輸入下方。

最好的方法是如何做到這一點?

我的想法是創建 2 個狀態,每個按鈕一個,它們將具有每個標簽所需的 div 數量。

const [textAreaNo,setTextAreaNo] = useState(0);
const [uploadNo,setUploadNo] = useState(0);

then after your buttons you can call the (addDiv) function, but u will have to create 2 different functions for each button, or just make one function and inside the function it will return upload or textArea depending on the passed parameter.

那么最后你需要像這樣使用map

{[...Array(textAreaNo)].map(e=>(
    <div> textbox <div>
  ))}

在你的按鈕上,我們只會增加上面的狀態,比如

 <button onClick={()=> setTextAreaNo(textAreaNo+1)}>AddDivs</button>

我不確定您是否希望能夠添加多個文本區域。 我會這樣做的一種方法是創建一個 state 項目,它知道您需要多少個文本區域,然后是一個 function,它在 onClick() 上增加這個數字。 您還需要一個返回文本框項目的 function。 像這樣的東西:

Class 組件:

this.state = {
    numberOfTextAreas: 0
}

const textAreas = () => { //<---------a function like this

for (let i = 0; i < this.state.numberOfTextAreas; i++) {
    return (
        <div>
           <textarea rows="4" placeholder="Write about sompething here..." /> 
        </div>
    );
}
}

const addDivs = (type) => { ??? }

export default function Form() {

handleSubmit(e) {...}

return ( 
<form onSubmit={handleSubmit}>
<div><textarea rows="4" placeholder="Write about something here..." /></div>


//New divs should go here
{textAreas} //<---- Add this here.


<button onClick={() => this.setState({numberOfTextAreas + 1})}>Add textarea</button>
//Adds an upload field
<button onClick={() => addDivs(upload)}>Add image</button>
<input type="submit" value="Submit" /> </form> ); 
}

```

然后你只想對你想要創建的其他類型做同樣的事情。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM