如果您已经具有用于单个FieldEditor的onChange处理函数,那么我不明白为什么您不能只将状态移到FormEditor组件上,而仅将回调从那里传递给FieldEditor,以更新父状态。对我来说,这似乎是一种更React-
y的方式。
可能与此类似:
const FieldEditor = ({ value, onChange, id }) => { const handleChange = event => { const text = event.target.value; onChange(id, text); }; return ( <div className="field-editor"> <input onChange={handleChange} value={value} /> </div> );};const FormEditor = props => { const [values, setValues] = useState({}); const handleFieldChange = (fieldId, value) => { setValues({ ...values, [fieldId]: value }); }; const fields = props.fields.map(field => ( <FieldEditor key={field} id={field} onChange={handleFieldChange} value={values[field]} /> )); return ( <div> {fields} <pre>{JSON.stringify(values, null, 2)}</pre> </div> );};// To add abillity to dynamically add/remove fields keep the list in stateconst App = () => { const fields = ["field1", "field2", "anotherField"]; return <FormEditor fields={fields} />;};
原始-钩前版本:
class FieldEditor extends React.Component { constructor(props) { super(props); this.handleChange = this.handleChange.bind(this); } handleChange(event) { const text = event.target.value; this.props.onChange(this.props.id, text); } render() { return ( <div className="field-editor"> <input onChange={this.handleChange} value={this.props.value} /> </div> ); }}class FormEditor extends React.Component { constructor(props) { super(props); this.state = {}; this.handleFieldChange = this.handleFieldChange.bind(this); } handleFieldChange(fieldId, value) { this.setState({ [fieldId]: value }); } render() { const fields = this.props.fields.map(field => ( <FieldEditor key={field} id={field} onChange={this.handleFieldChange} value={this.state[field]} /> )); return ( <div> {fields} <div>{JSON.stringify(this.state)}</div> </div> ); }}// Convert to class component and add ability to dynamically add/remove fields by having it in stateconst App = () => { const fields = ["field1", "field2", "anotherField"]; return <FormEditor fields={fields} />;};ReactDOM.render(<App />, document.body);
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)