javascript - React Hooks - 如何重构这些动态生成的输入?

标签 javascript reactjs refactoring

我正在尝试使用动态创建的输入,并且想知道如何让代码变得更好。

想法是有一个“配置”对象来确定输入生成。

我对所有建议都很感兴趣,例如更好的模式、重命名变量/组件/css 类、移动代码、可能的问题、效率低下...

我可能的改进是将输入状态移动到 Inputs 组件中,而不是当前的 Journal 组件中。不确定这是否是个好主意...

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;

Input.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>

Demo Screenshot

enter image description here

关于javascript - React Hooks - 如何重构这些动态生成的输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58584144/

相关文章:

javascript - 如何检查字符串是否为合法的 "dd/mm/yyyy"日期?

reactjs - html-webpack-plugin 入口点未定义=index.html

reactjs - 在 create-react-app 中高效导入多个相似的 svg 源?

javascript - 使用回调函数和异步请求时避免重复

c++ - 高效处理为redis(hiredis)的SET命令创建模板

c++ - 有没有更优雅的方法来实现 C++ 游戏的 "cheat code"实现?

javascript - JavaScript 中是否可以使用 RegExp 来匹配不同的特定长度?

javascript - 替换 URL 中最后一个字符之后的所有内容

javascript - 如何让vue每天只显示一次弹出窗口

javascript - 如何使用 es6 语法导入 ReactCSSTransitionGroup?