About React Refs

First, what is ref

React ref attribute is provided for operation of the elements DOM

 

 

Second, the ref ways

 

1, string pattern

Binding ref attribute XX, obtained by this.refs.XX

class refTest extends React.Component {
  constructor(props) {
    super(props);
    this.state = {

    }
  }

  handleClick() {
    console.log(this.refs.inputElem.value)
  }

  render() {
    return (
      <React.Fragment>
      <div>
        <input type="text" ref="inputElem" />
      </div>
      <button onClick={this.handleClick.bind(this)}>toConsole</button>
      </React.Fragment>
    )
  }
}

String pattern does not support static type checking, and is not recommended React

 

2, the callback function mode

Callback function is provided in the ref attribute, obtained by this.XX

class refTest extends React.Component {
  constructor(props) {
    super(props);
    this.state = {

    }
  }

  handleClick() {
    console.log(this.inputElem.value)
  }

  render() {
    return (
      <React.Fragment>
      <div>
        <input type="text" ref={(input) => this.inputElem = input} />
      </div>
      <button onClick={this.handleClick.bind(this)}>toConsole</button>
      </React.Fragment>
    )
  }
}

operation result:

Click "toConsole" in the console output: 

The callback function mode supports static type checking

 

Guess you like

Origin www.cnblogs.com/Leophen/p/11326600.html