“Composant de la classe Useref React” Réponses codées

useRef () in React

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>
    </>
  );
}
Salo Hopeless

Réaction du composant de la classe UseReref

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

Qu'est-ce que Useref réagit

const refContainer = useRef(initialValue);
//useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). 
//The returned object will persist for the full lifetime of the component.
Happy Hamster

Exemple Useref

import { useRef } from "react";

function ExampleUseRef() {
  const inputNode = useRef(null);

  const onClick = () => {
    inputNode.current.focus();
  };

  return (
    <>
      <input ref={inputNode} type="text" />
      <button onClick={onClick}>Focus..</button>
    </>
  );
}
EfficientCoder

Composant de la classe Useref React

class CustomTextInput extends React.Component {
  constructor(props) {
    super(props);
    // create a ref to store the textInput DOM element
    this.textInput = React.createRef();
    this.focusTextInput = this.focusTextInput.bind(this);
  }

  focusTextInput() {
    // Explicitly focus the text input using the raw DOM API
    // Note: we're accessing "current" to get the DOM node
    this.textInput.current.focus();
  }

  render() {
    // tell React that we want to associate the <input> ref
    // with the `textInput` that we created in the constructor
    return (
      <div>
        <input
          type="text"
          ref={this.textInput} />
        <input
          type="button"
          value="Focus the text input"
          onClick={this.focusTextInput}
        />
      </div>
    );
  }
}
Dev Mahir

Réponses similaires à “Composant de la classe Useref React”

Questions similaires à “Composant de la classe Useref React”

Plus de réponses similaires à “Composant de la classe Useref React” dans JavaScript

Parcourir les réponses de code populaires par langue

Parcourir d'autres langages de code