开发者问题收集

如何使用“ref”引用 React Stateless Component 中的元素

2020-02-18
346

我尝试使用 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>
  )
}

它给出以下错误。

未捕获的类型错误:无法设置未定义的属性“createLabelBtn”

未捕获的类型错误:无法设置未定义的属性“createLabelBtn”

这里可能是什么问题?

2个回答

函数式组件是无实例的,因此没有 this 来绑定或调用任何东西。将按钮上的 ref 属性设置为 ref={createLabelBtn ,并设置焦点,您需要访问 createLabelBtn.current 以获取 ref 的当前值。

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

Drew Reese
2020-02-18

尝试一下

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;
Dhammika Saman Kumara
2020-02-18