Как сослаться на такие методы документа, как getElementByID, в файле tsx? - PullRequest
1 голос
/ 09 июля 2020

Я конвертирую простые файлы js в машинописный текст в приложении React.

document показывает ошибку, когда я использую такие методы, как document.getElementById("login-username")

Как можно Я имею в виду document методы в этом машинописном документе?

import React, { useState, FormEvent, ChangeEvent } from 'react';

interface loginProps {
  username: string,
  setUsername(username: string): string,
  setLoggedIn(loggedIn: boolean): boolean
}

export default function Login(props: loginProps) {
  const { username, setUsername, setLoggedIn } = props;
  const [err, setErr] = useState('');
  function handleUsername(e: FormEvent<HTMLFormElement> ) {
    const user = document.getElementById("login-username").value.trim();
    const password = document.getElementById("login-password").value.trim();
    if (user === '') { setErr('blank username'); } else {  //ugly, will fix later
      if (password === '') { setErr('blank password'); } else {
        if (user.length < 2) { setErr('username must be at least 2 characters'); } else {
          setUsername(user);
          setLoggedIn(true);
        }
      }
    }
    e.preventDefault();
  }
  function setUserField(e: ChangeEvent<HTMLInputElement>) {
    setUsername(e.target.value);
    e.preventDefault();
  }
  return (
    <form onSubmit={handleUsername} autoComplete="yes" style={{ padding: "10px" }}>
      <span style={{ fontWeight: 'bold' }}>Login</span>
      <br /><br />
      <label htmlFor="login-username">Username:</label>
      <input type="text" 
        padding="20px"
        value={username}
        onChange={setUserField}
        name="login-username"
        id="login-username" />
      <label htmlFor="login-password">Password:</label>
      ...

1 Ответ

1 голос
/ 09 июля 2020

Итак, в ReactJS лучше всего использовать refs https://reactjs.org/docs/refs-and-the-dom.html

 class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }
  render() {
    return <div ref={this.myRef} />;
  }
}

В основном создайте переменную для доступа к вашему элементу. Добавьте атрибут ref к указанному элементу и назначьте ему переменную. После этого у вас будет доступ к элементу в DOM в соответствии со стандартом React.

EDIT:

Вот пример из документации с использованием хуков, useRef

function TextInputWithFocusButton() {
  const inputEl = useRef(null);
  const onButtonClick = () => {
    // `current` points to the mounted text input element
    inputEl.current.focus();
  };
  return (
    <>
      <input ref={inputEl} type="text" />
      <button onClick={onButtonClick}>Focus the input</button>
    </>
  );
}
...