[英]React Hooks - How can I refactor these dynamically generated inputs?
我正在嘗試使用動態創建的輸入,並且想知道如何使代碼更好。
這個想法是有一個“配置” object 來確定輸入生成。
我對所有建議都很感興趣,比如更好的模式、重命名變量/組件/css-classes、移動代碼、可能的問題、效率低下......
我可能的改進是將輸入 state 移動到Inputs
組件內,而不是當前的Journal
組件內。 不確定這是不是個好主意...
日記.js
import React, { useState, useEffect } from "react";
import Inputs from '../layout/Inputs';
function Journal(props) {
const [inputsJournalItems, setInputsJournalItems] = useState({
documentKey: "",
documentDate: ""
});
// generic handler based on the input name
const handleInputChange = e => {
setInputsJournalItems({
...inputsJournalItems,
[e.target.name]: e.target.value
})
}
// log the state after re-render
useEffect(() => {
console.log(inputsJournalItems)
}, [inputsJournalItems]);
// how to avoid including the handler for each input?
const inputs = [
{ type: "input", label: "Document", name: "documentKey", handleInputChange },
{ type: "input", label: "Date", name: "documentDate", handleInputChange },
{ type: "button", value: "Save", name: "save" },
];
return (
<div>
<Inputs
data={inputsJournalItems}
inputs={inputs} />
</div >
)
}
export default Journal;
Inputs.js
import React from 'react';
import Input from '../layout/Input';
function Inputs(props) {
return (
<div className="inputs">
{
props.inputs.map(input => {
return (
<Input
type={input.type}
label={input.label}
name={input.name}
handleInputChange={input.handleInputChange}
value={input.value ? input.value : props.data[input.name]}
>
</Input>
)
})
}
</div>
)
}
export default Inputs;
輸入.js
import React from 'react';
function Input(props) {
let inputId = `input-${props.name}`;
return (
<div className="input-group">
<label>{props.label}</label><br></br>
<input
type={props.type}
id={inputId}
name={props.name}
onChange={props.handleInputChange}
value={props.value}
/>
</div>
)
}
export default Input;
我有一些建議和一些修改可能會讓您的事情變得更清潔和可維護:
你可以在codesandbox.io上查看
或者通過運行下面的代碼片段
<iframe src="https://codesandbox.io/embed/nervous-snow-sefyi?fontsize=14" style="width:100%; height:500px; border:0; border-radius: 4px; overflow:hidden;" title="nervous-snow-sefyi" allow="geolocation; microphone; camera; midi; vr; accelerometer; gyroscope; payment; ambient-light-sensor; encrypted-media; usb" sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin" ></iframe>
演示截圖
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.