Ich habe Form mit Reagieren viele Male gemacht, jedes Mal kam ich mit einem besseren Weg. Um es einfach zu halten, kann ich Ihnen eine sehr einfache Vorstellung davon geben, wie Sie es angehen können.
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);
}
}
Beachten Sie, dass Sie verhindern möchten, dass das Formular Statusänderungen verursacht, da Sie die tatsächlichen Eingaben und Schaltflächen rendern. Es wird dazu führen, dass alle Komponenten neu gerendert werden. So können wir die Werte verfolgen, ohne wirklich irgendwelche Zustände zu ändern. und die onChange
, die wir auf die Komponente selbst reserviert haben.
Ich benutze Redux-Form, um mir mit großen Formen zu helfen. Wenn Sie redux verwenden, dann ist es einen Blick wert. – ctrlplusb
http://redux-form.com – ctrlplusb
Mein Tipp wäre OnChange Event-Handler (jeder Eingang kann die gleiche Methode aufrufen). Auf lange Sicht ist es das wert. – wintvelt