从按钮重置文件类型输入

Reset a file type input from a button

提问人:Aurélie 提问时间:6/5/2023 最后编辑:Lin DuAurélie 更新时间:6/5/2023 访问量:39

问:

我无法在我的 Form.control {file} 中分配一个值,该值的类型为 File |null,因为它指示

键入“文件|null“不可分配给类型”string |数字 |字符串[] |未定义”。 类型“null”不能分配给类型“string |数字 |字符串[] |未定义'.ts(2322)

我已经尝试使用 useRef 并为我的输入分配一个 ref,但这也不起作用......

这是我的基本代码: 我评论了这个问题

const ValidatorHome: FunctionComponent = () => {

  const [resource, setResource] = useState("");
  const [profiles, setProfiles] = useState([] as { name: string, url: string }[]);
  const [selectedProfile, setSelectedProfile] = useState("");
  const [file, setFile] = useState(null as File | null);
  const [loading, setLoading] = useState(false);

  const navigate = useNavigate();

  const fhirClient = new Client({
    baseUrl: 'http://localhost:3000/fhir'
  });

  useEffect(() => {
    loadProfiles();
  }, []);

  /**
    * Load Profiles from the back to populate Validation report page.
    * 
    * @returns the promise of a Structure Definition.
    */
  async function loadProfiles() {
    setLoading(true);
    try {
      const response = await fhirClient.search({
        resourceType: 'StructureDefinition',
        searchParams: {
          "_elements": "name,url",
          "_count": "12222222"
        }
      })
      const results: Bundle = response as Bundle;
      const profiles: { name: string; url: string; }[] = [];
      results.entry?.forEach(e => {
        const profile = e.resource as StructureDefinition;
        profiles.push({ name: profile.name, url: profile.url });
      })
      setProfiles(profiles);
      setLoading(false);
    } catch (error) {
      //TODO Do better error handling
      console.log(error);
    }
  }

 /**
    * Reset the values of the resource, the resource of the file and the option of the select.
    */
  function onReset() {
    setLoading(true);
    setResource("");
    setSelectedProfile("");
    setFile(null);
    setLoading(false);
  }

  return (
    <div>
      <Header title1Key={i18n.t('validator.title')} />
      {loading ? (<>
        <Loader />
        <div className={styles.footerContainer}>
          <Footer />
        </div >
      </>) : (
        <>
          {loading && (
            <Loader />
          )}
          <>
            <div className={styles.main}>
              <Form.Group>
                <Form.Label className={styles.formLabel}>
                  {i18n.t('validator.labels.fhirResource')}
                </Form.Label>
                <Form.Control
                  as="textarea"
                  value={resource}
                  rows={5}
                  placeholder={i18n.t('validator.textarea.placeHolder').trimEnd()}
                  type="text"
                  onChange={(e) => setResource(e.target.value)} />
              </Form.Group>
              <fieldset
                id="uploadInput"
              >
                <Form.Group
                  controlId="formFile"
                  className="mb-3"
                >
                  <Form.Label className={styles.formLabel}>
                    {i18n.t('validator.labels.uploadResource')}
                  </Form.Label>
                  <Form.Control
                    // My problem is here : Type 'File | null' is not assignable to type 'string | number | string[] | undefined'.
                    // Type 'null' is not assignable to type 'string | number | string[] | undefined'.ts(2322)
                    // value={file}
                    id="fileInput"
                    type="file"
                    onChange={(e) => {
                      const target = e.target as HTMLInputElement;
                      setFile(target.files ? target.files[0] : null);
                    }}
                  />
                </Form.Group>
              </fieldset>
              <Form.Group>
                <Form.Label className={styles.formLabel}>
                  {i18n.t('validator.labels.selectProfile')}
                </Form.Label>
                <Form.Select
                  value={selectedProfile}
                  aria-label="Default select example"
                  onChange={(e) => {
                    setSelectedProfile(e.target.value);
                  }}
                >
                  <option>{i18n.t('validator.labels.defaultProfileOption')}</option>
                  {profiles.map(profile => getProfileOptions(profile))}
                </Form.Select>
              </Form.Group>
              <div className={styles.buttonsContainer}>
                <Button
                  className={styles.validatebutton}
                  variant="danger"
                  onClick={sendToValidation}
                >
                  {i18n.t('validator.button.validate')}
                </Button>
                <Button
                  className={styles.resetbutton}
                  variant="secondary"
                  onClick={onReset}
                >
                  {i18n.t('validator.button.reset')}
                </Button>
              </div>
            </div>
            <Footer />
          </>
        </>
      )}
    </div >
  );
};

export default ValidatorHome;
reactjs 文件 输入 react-hooks 重置

评论

0赞 Hellma 6/5/2023
File 是 Blob 的一种类型,它们是不可变的 (developer.mozilla.org/en-US/docs/Web/API/Blob)。这应该可以解释为什么你不能为文件变量分配一个新值。也许这有助于解决您的问题。

答: 暂无答案