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

React refs

new

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


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>
    );
  }
}

old

https://github.com/xgqfrms/React/issues/4

https://github.com/xgqfrms/React/issues/7

https://zhenyong.github.io/react/docs/more-about-refs.html#the-ref-string-attribute

https://react2.xgqfrms.xyz/docs/more-about-refs.html#ref-string-属性


var MyComponent = React.createClass({
  handleClick: function() {
    // Explicitly focus the text input using the raw DOM API.
    this.myTextInput.focus();
  },
  render: function() {
    // The ref attribute adds a reference to the component to
    // this.refs when the component is mounted.
    return (
      <div>
        <input type="text" ref={(ref) => this.myTextInput = ref} />
        <input
          type="button"
          value="Focus the text input"
          onClick={this.handleClick}
        />
      </div>
    );
  }
});

ReactDOM.render(
  <MyComponent />,
  document.getElementById('example')
);

原文地址:https://www.cnblogs.com/xgqfrms/p/10117877.html