xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

React refs All In One

React refs All In One

DOM ref

useRef 👍✅

https://reactjs.org/docs/forwarding-refs.html


function CustomTextInput(props) {
  // textInput must be declared here so the ref can refer to it
  const textInput = useRef(null);
  
  function handleClick() {
    textInput.current.focus();
  }

  return (
    <div>
      <input
        type="text"
        ref={textInput} />
      <input
        type="button"
        value="Focus the text input"
        onClick={handleClick}
      />
    </div>
  );
}

https://reactjs.org/docs/refs-and-the-dom.html#refs-and-function-components

function MyFunctionComponent() {
  return <input />;
}

class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.textInput = React.createRef();
  }
  render() {
    // This will *not* work!
    return (
      <MyFunctionComponent ref={this.textInput} />
    );
  }
}

React.createRef 👍✅

https://reactjs.org/docs/refs-and-the-dom.html#creating-refs

class MyComponent extends React.Component {
  constructor(props) {
    super(props);

    this.inputRef = React.createRef();
  }

  render() {
    return <input type="text" ref={this.inputRef} />;
  }

  componentDidMount() {
    this.inputRef.current.focus();
  }
}

callback ref 👍✅

https://reactjs.org/docs/refs-and-the-dom.html#callback-refs


string ref 👎❌

https://reactjs.org/docs/refs-and-the-dom.html#legacy-api-string-refs


refs

strict mode

https://reactjs.org/docs/strict-mode.html#warning-about-legacy-string-ref-api-usage



©xgqfrms 2012-2020

www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!


posted @ 2020-09-25 22:22  xgqfrms  阅读(132)  评论(4)    收藏  举报