首页 > 解决方案 > 重置通知状态时,Material UI Autocomplete 组件不会清除输入

问题描述

我正在使用 Material UI 版本 4(最新)和Informed form library。我有一个自定义组件(自定义以与 Informed 集成),它包装了我使用 Autocomplete 组件呈现的 Material UI TextField。

应用组件

    <Form getApi={(api) => setFormApi(api)}>
      {formApi && (
        <>
          <label>
            First name:
            <Autocomplete
              freeSolo
              options={autoOptions}
              renderInput={(params) => (
                <CustomTextField field="name" {...params} />
              )}
            />
          </label>
          <button type="submit">Submit</button>
          <button type="button" onClick={() => formApi.reset()}>
            Reset
          </button>
          <FormState />
        </>
      )}
    </Form>

问题

单击重置按钮时,您可以看到 Informed“表单状态”被清除,但输入仍然有一个值。关于如何解决这个问题的任何想法?

示例 - Codesandbox

标签: javascriptreactjs

解决方案


inputProps正在被组件提供的覆盖,Autocomplete更改您传递...rest道具的顺序并使用正确的值包含...rest.inputProps在您的自定义中inputProps

      <TextField
        {...rest} // should go first to allow overriding
        // only add value props for select fields
        // value={value}
        onChange={(event) => {
          setValue(event.target.value);
          if (onChange) {
            onChange(event);
          }
        }}
        onBlur={(event) => {
          setTouched(true);
          if (onBlur) {
            onBlur(event);
          }
        }}
        error={!!error}
        helperText={error ? error : helperText ? helperText : false}
        variant="outlined"
        margin="none"
        fullWidth
        inputProps={{
          ...rest.inputProps, // must include otherwise it breaks
          value:
            !select && !maskedValue && maskedValue !== 0 ? "" : maskedValue,
          maxLength: maxLength || undefined
        }}
        // eslint-disable-next-line
        InputProps={{
          style: sensitive && {
            color: "rgba(0,0,0,0)",
            caretColor: "#000"
          },
          startAdornment
        }}
        InputLabelProps={{
          shrink: true
        }}
        autoComplete="off"
        disabled={disabled}
      />

推荐阅读