Как использовать «ref» для ссылки на элемент в React Stateless Component - PullRequest
0 голосов
/ 18 февраля 2020

Я пытался установить фокус для кнопки Отправить с помощью Ref. Я хотел опустить реферирующие элементы по ID.

import React, { useRef } from 'react'
import PropTypes from 'prop-types'

export const LabelComponent = () => {

  const createButton = enableCreateButton()
    ? <button ref={(input) => { this.createLabelBtn = input }} >Submit</button>
    : <button disabled ref={(input) => { this.createLabelBtn = input }} >Submit</button>

  const createLabelBtn = useRef();

  const focusCreateBtn = (e) => {
    if ((e.key === 'Enter') && (newLabel.name !== '')) {
      this.createLabelBtn.focus();
    }
  };

  return (
    <div className='create-label-container'>
      <input type='text'
        onKeyDown={(e) => { focusCreateBtn(e) }}
      />

      {createButton}
    </div>
  )
}

Это выдает следующую ошибку.

Uncaught TypeError: Невозможно установить свойство 'createLabelBtn' из неопределенного

Uncaught TypeError: Невозможно установить свойство 'createLabelBtn' из неопределенного

В чем здесь может быть проблема .?

Ответы [ 2 ]

1 голос
/ 18 февраля 2020

Функциональные компоненты не имеют экземпляров, поэтому this не нужно связывать или вызывать. Установите опору ref на кнопке так же, как и ref={createLabelBtn}, и для установки фокуса вам необходимо получить доступ к createLabelBtn.current, чтобы получить текущее значение ссылки.

export const LabelComponent = ({ enableCreateButton }) => {
  const createLabelBtn = useRef(null);

  const focusCreateBtn = e => {
    if (e.key === "Enter") {
      createLabelBtn.current.focus();
    }
  };

  return (
    <div className="create-label-container">
      <input type="text" onKeyDown={focusCreateBtn} />
      <button
        // upon being focused upon, console log proof
        onFocus={() => console.log("Submit Focused!")}
        disabled={!enableCreateButton}
        ref={createLabelBtn}
      >
        Submit
      </button>
    </div>
  );
};

Edit strange-wood-chou6

0 голосов
/ 18 февраля 2020

Попробуйте это

import React, { useRef, useState } from "react";

const LabelComponent = () => {
  const [name, setName] = useState("");

  const createButton = true ? (
    <button
      ref={input => {
        createLabelBtn.current = input;
      }}
    >
      Submit
    </button>
  ) : (
    <button
      disabled
      ref={input => {
        createLabelBtn.current = input;
      }}
    >
      Submit
    </button>
  );

  const createLabelBtn = useRef();

  const focusCreateBtn = e => {
    if (e.key === "Enter" && name !== "") {
      createLabelBtn.current.focus();
    }
  };

  return (
    <div className="create-label-container">
      <input
        type="text"`enter code here`
        value={name}
        onChange={e => {
          setName(e.target.value);
        }}
        onKeyDown={e => {
          focusCreateBtn(e);
        }}
      />

      {createButton}
    </div>
  );
};

export default LabelComponent;
...