我正在阅读有关反应表单的内容,我只能阅读有关表单中数据管理的两种方法。
第一个 - refs
,将refs放在每个数据输入中:
class CustomTextInput extends React.Component {
constructor(props) {
super(props);
this.focus = this.focus.bind(this);
}
focus() {
// Explicitly focus the text input using the raw DOM API
this.textInput.focus();
}
render() {
// Use the `ref` callback to store a reference to the text input DOM
// element in this.textInput.
return (
<div>
<input
type="text"
ref={(input) => { this.textInput = input; }} />
<input
type="button"
value="Focus the text input"
onClick={this.focus}
/>
</div>
);
}
}
和第二个受控表格,为每个数据输入设置一个处理程序:
import React, { Component } from 'react';
import Form from 'react-form-controlled';
export default class Example extends Component {
constructor(props, context) {
super(props, context);
this.state = {
users: [{
firstName: 'Zlatko'
}, {
firstName: 'Livia'
}]
};
}
onChange = (data) => {
this.setState(data);
}
onSubmit = (data) => {
alert(`Hi ${data.users[0].firstName}`);
}
render() {
return (
<Form
value={this.state}
onChange={this.onChange}
onSubmit={this.onSubmit}
>
<fieldset name="users">
<label>
<input name="firstName" />
</label>
</fieldset>
<button type="submit">Submit</button>
</Form>
);
}
}
因此,假设您有一个包含大量数据输入的大型表单,您是否必须为表单中的每个输入声明所有处理函数? (另外,构造函数中的绑定总数)
仅提交刚刚阅读的form.input1
,form.input2
是否方便?我的意思是,像这样的人:
onSubmit(formValues){
payload = [
{'value1': formValues.input1 },
{'value2': formValues.input2 },
...
{'valueN': formValues.inputN },
]
}
无需从state
阅读
无论如何,拥有一个带有大量处理程序的智能组件来管理表单值是否有用?或者可能是另一种方法,对于表单中的每个组件都有refs
?
答案 0 :(得分:1)
我建议您检查redux
+ redux-form
组合。使用这些模块管理表单状态就是一个案例。您可以拥有没有任何本地状态或处理程序的功能组件。