【发布时间】:2018-07-12 04:14:54
【问题描述】:
我正在尝试使用 react-jsonschema-form 和 react-jsonschem-form-conditionals 从 JSON 模式构建一个带有条件字段的表单。
我正在渲染的组件是FormWithConditionals 和FormModelInspector。后者是一个非常简单的组件,展示了表单模型。
相关源码为:
import React from 'react';
import PropTypes from 'prop-types';
import Engine from "json-rules-engine-simplified";
import Form from "react-jsonschema-form";
import applyRules from "react-jsonschema-form-conditionals";
function FormModelInspector (props) {
return (
<div>
<div className="checkbox">
<label>
<input type="checkbox" onChange={props.onChange} checked={props.showModel}/>
Show Form Model
</label>
</div>
{
props.showModel && <pre>{JSON.stringify(props.formData, null, 2)}</pre>
}
</div>
)
}
class ConditionalForm extends React.Component {
constructor (props) {
super(props);
this.state = {
formData: {},
showModel: true
};
this.handleFormDataChange = this.handleFormDataChange.bind(this);
this.handleShowModelChange = this.handleShowModelChange.bind(this);
}
handleShowModelChange (event) {
this.setState({showModel: event.target.checked});
}
handleFormDataChange ({formData}) {
this.setState({formData});
}
render () {
const schema = {
type: "object",
title: "User form",
properties: {
nameHider: {
type: 'boolean',
title: 'Hide name'
},
name: {
type: 'string',
title: 'Name'
}
}
};
const uiSchema = {};
const rules = [{
conditions: {
nameHider: {is: true}
},
event: {
type: "remove",
params: {
field: "name"
}
}
}];
const FormWithConditionals = applyRules(schema, uiSchema, rules, Engine)(Form);
return (
<div className="row">
<div className="col-md-6">
<FormWithConditionals schema={schema}
uiSchema={uiSchema}
formData={this.state.formData}
onChange={this.handleFormDataChange}
noHtml5Validate={true}>
</FormWithConditionals>
</div>
<div className="col-md-6">
<FormModelInspector formData={this.state.formData}
showModel={this.state.showModel}
onChange={this.handleShowModelChange}/>
</div>
</div>
);
}
}
ConditionalForm.propTypes = {
schema: PropTypes.object.isRequired,
uiSchema: PropTypes.object.isRequired,
rules: PropTypes.array.isRequired
};
ConditionalForm.defaultProps = {
uiSchema: {},
rules: []
};
但是,每次我更改字段的值时,该字段都会失去焦点。我怀疑问题的原因是在react-jsonschema-form-conditionals 库中,因为如果我将<FormWithConditionals> 替换为<Form>,则不会出现问题。
如果我删除处理程序 onChange={this.handleFormDataChange},则输入字段在值更改时不再失去焦点(但删除此处理程序会破坏 FormModelInspector)。
一边
在上面的代码中,如果我删除处理程序onChange={this.handleFormDataChange},当表单数据更改时<FormModelInspector> 不会更新。我不明白为什么这个处理程序是必要的,因为<FormModelInspector> 通过formData 属性传递了对表单数据的引用。也许是因为表单数据的每一次更改都会导致构造一个新对象,而不是修改同一个对象?
【问题讨论】:
标签: forms reactjs jsonschema