我有一部分这样的组件:(它使用mobx-react-form)
...
<div className={styles.flexWrapper}>
{
this.localState.isCompanyFieldToggled
?
locationCompany.list ?
<div className={styles.selectContainer}>
<VirtualizedSelect
className={styles.virtualizedSelect}
placeholder="Company"
clearable={false}
searchable={true}
options={locationCompany.list}
onFocus={(): void => locationCompany.onFocus()}
onChange={(selectedValue: Object) => this.setResult(selectedValue)}
isLoading={locationCompany.loading}
noResultsText="Loading..."
value={locationCompany.selected}
labelKey="name"
valueKey="id"
/>
<InputLabel
className="Select-custom-placeholder">
Company
</InputLabel>
</div> : null
:
<ElectroTextField field={this.props.form.$('projectLocation.locationCompany')} />
}
<ElectroButton className={styles.button} onClick={this.toggleCompanyField} color="primary" label={this.localState.isCompanyFieldToggled ? 'add new' : 'choose company'}/>
</div>
...
和“ toggleCompanyField”在VirtualizedSelect和ElectroTextField之间切换。
toggleCompanyField = (e) => {
const field = this.props.form.$('projectLocation.locationCompany')
this.localState = {
isCompanyFieldToggled: !this.localState.isCompanyFieldToggled
}
console.log(field.value !== '')
if(this.localState.isCompanyFieldToggled === false){
this.locationCompany.setResult()
}
else {
if(field.value !== ''){
field.clear()
}
}
}
,“ ElectroTextField”组件为:
const ElectroTextField: React.StatelessFunctionalComponent<*> = observer(({
field
}: Object) => {
return (
<TextField
{...field.bind()}
error={field.hasError}
helperText={field.showError ? field.error : ''}
required={field.rules === 'required'}
margin="normal"
/>
);
});
export default ElectroTextField;
为示例中显示的字段设置的规则是:
...
name: 'projectLocation',
label: 'Project Location',
fields: [
{
name: 'locationCompany',
label: 'Company',
placeholder: 'Company name...',
rules: 'required',
value: ''
}]
}
...
如果我在“ ElectroTextField”中有一个值并且切换到VirtualizedSelect,则该值将保留在“ ElectroTextField”中。
我尝试使用“ clear”和“ reset”方法,但是尽管它们确实清除了字段,但它们还触发了验证,由于用户尚未与输入进行交互,因此此时不应触发验证。
https://foxhound87.github.io/mobx-react-form/docs/api-reference/fields-methods.html