我的 React 中有以下代碼:
const [property, setProperty] = useState([]);
const [state, setState] = React.useState({ type: "", propertyName: "" });
const handleChange = (e, inputField) => {
setState((prevState) => ({
...prevState,
[inputField]: e.target.value,
}));
};
const handleSubmit = () => {
if (state.type !== "" && state.propertyName !== "") {
const newObject = { type: state.type, propertyName: state.propertyName };
property.push(newObject);
console.log(property);
setState({
type: "",
propertyName: "",
});
}
};
和html:
<div>
<label htmlFor='properties' className='properties-label'>
Properties
</label>
<div className='property-box'>
<input
type='text'
id='type'
value={state.type}
placeholder='Type'
className='type-element'
required
onChange={(e) => handleChange(e, "type")}
></input>
<input
type='text'
id='name'
value={state.propertyName}
className='type-element'
placeholder='Name'
required
onChange={(e) => handleChange(e, "propertyName")}
></input>
<button
className='buttonAccount'
type='submit'
onClick={handleSubmit}
>
Add Property
</button>
</div>
</div>
我想要的是當我按下添加屬性按??鈕時,一個新的 html 標記將呈現在頁面上(一個框或類似的東西,包含已輸入的兩個欄位)。你能幫我找到一種方法嗎?
uj5u.com熱心網友回復:
您必須列印property陣列中的元素。例如:
{
property.map((element) => (
<div key={element.propertyName}>
<span>
{element.type}
</span>
<span>
{element.propertyName}
</span>
</div>
)
}
uj5u.com熱心網友回復:
您可以使用 Javascript 陣列map方法將您property狀態中的每個專案映射到 HTML 元素。
例如:
- 創建一個函式,將映射
property狀態回傳到 HTML 元素中。
const renderProperties = () => {
return property.map((item, index) => (
// `item` is a representation of each of your object in the property array
// In this case, item contains { type: string, propertyName: string }
<div key={index}> // React requires user to put a key in each of the mapped component
<p>{item.propertyName}</p>
<p>{item.type}</p>
</div>
))
}
- 在 JSX 的 HTML 部分中呼叫此函式。
...
<button
className='buttonAccount'
type='submit'
onClick={handleSubmit}
>
Add Property
</button>
</div>
{renderProperties()} // <-- Here
</div>
https://reactjs.org/docs/lists-and-keys.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/432988.html
標籤:javascript html 反应
上一篇:ReactTS變數未定義
