使用 ES6 类时,具有许多表单输入的 react 组件的典型实现是什么?



实现具有许多表单输入的 react 组件的典型方法是什么?

每个输入上的onChangeEvent似乎不切实际。

ES6 组件中不再混合用于双向绑定帮助程序。

还是应该在需要时只使用元素引用来读取输入值?

我已经用

反应制作了很多次表格,每次我都带着更好的方法来了。为了简单起见,我可以给你一个非常基本的想法,告诉你如何处理它。

class Form extends Component
{
    fields = {};
    constructor(props)
    {
        super(props);
        let components = this.bindComponents();
        this.state = {};
        this.state.components = components;
    }
    render()
    {
        const { components } = this.state;
        return DOM.div({}, components);
    }
    bindComponents()
    {
        let children = this.props.children;
        children = React.Children.map(children, child =>
        {
            if (typeof child != "object" || !child.props)
                return child;
            let props = Object.assign({}, child.props);
            if (props.name)
            {
                props.onChange = (event) =>
                {
                    let value = event.target.value;
                    // Allow other parents to listen to this event
                    if (child.props.onChange)
                        child.props.onChange(value);
                    this.fields[props.name] = value;
                };
            }
            return React.cloneElement(child, props);
        });
        return children;
    }
    /**
     * You can use this in buttons and etc ..
     * Or like the onChange of the input you can do the same with onClick on buttons,
     * and when the button clicked you can trigger this event
     */
    onSubmit()
    {
        if (this.props.onSubmit)
            this.props.onSubmit(this.fields);
    }
}

请注意,您希望防止表单导致任何状态更改,因为如果您呈现实际的输入和按钮。 它将导致所有组件重新渲染..因此我们可以跟踪值而无需真正更改任何状态。 以及我们保留的组件本身的onChange

最新更新