Refs - rkaku/udemy-graphql-with-react-intro-search-repos GitHub Wiki

const App = () => {

  const input = useRef(null)

  return (
    <>
      <input ref={ input }/>
      <button onClick={() => { input.current.focus() }}>
        Focus :)
      </button>
    </>
  )
}
const FancyButton = React.forwardRef((props, ref) => (
  <button ref={ref} className="FancyButton">
    {props.children}
  </button>
))

// You can now get a ref directly to the DOM button:
const ref = React.createRef()
<FancyButton ref={ref}>Click me!</FancyButton>
function CustomTextInput(props) {
  // ref が参照できるように、textInput をここで宣言する必要があります。
  let textInput = React.createRef()

  function handleClick() {
    textInput.current.focus()
  }

  return (
    <div>
      <input
        type="text"
        ref={textInput} />

      <input
        type="button"
        value="Focus the text input"
        onClick={handleClick}
      />
    </div>
  )
}
function AddTodo() {
  let input;
  const [addTodo, { data }] = useMutation(ADD_TODO)

  return (
    <div>
      <form
        onSubmit={e => {
          e.preventDefault()
          addTodo({ variables: { type: input.value } })
          input.value = ''
        }}
      >
        <input
          ref={node => {
            input = node
          }}
        />
        <button type="submit">Add Todo</button>
      </form>
    </div>
  )
}
class CustomTextInput extends React.Component {
  constructor(props) {
    super(props)

    this.textInput = null

    this.setTextInputRef = element => {
      this.textInput = element
    }

    this.focusTextInput = () => {
      // 生の DOM API を使用して明示的にテキストの入力にフォーカスします。
      if (this.textInput) this.textInput.focus()
    }
  }

  componentDidMount() {
    // マウント時に入力をオートフォーカスします。
    this.focusTextInput()
  }

  render() {
    // インスタンスフィールド(例えば this.textInput)にテキスト入力の DOM 要素への
    // 参照を保存するために `ref` コールバックを使用してください。
    return (
      <div>
        <input
          type="text"
          ref={this.setTextInputRef}
        />
        <input
          type="button"
          value="Focus the text input"
          onClick={this.focusTextInput}
        />
      </div>
    )
  }
}
function CustomTextInput(props) {
  return (
    <div>
      <input ref={props.inputRef} />
    </div>
  )
}

class Parent extends React.Component {
  render() {
    return (
      <CustomTextInput
        inputRef={el => this.inputElement = el}
      />
    )
  }
}
⚠️ **GitHub.com Fallback** ⚠️