Refs

Các ref được sử dụng để trả về một tham chiếu đến phần tử. Refs nên tránh trong hầu hết các trường hợp, tuy nhiên, chúng có thể hữu ích khi chúng ta cần các phép đo DOM hoặc để thêm các phương thức vào các component.

Sử dụng Refs

Ví dụ sau đây cho thấy cách sử dụng refs để xóa trường nhập. Hàm ClearInput tìm kiếm phần tử có giá trị ref = "myInput" , đặt lại trạng thái và thêm tiêu điểm vào phần tử đó sau khi nhấp vào nút.

App.jsx

import React from 'react';

import ReactDOM from 'react-dom';

 

class App extends React.Component {

   constructor(props) {

      super(props);

             

      this.state = {

         data: ''

      }

      this.updateState = this.updateState.bind(this);

      this.clearInput = this.clearInput.bind(this);

   };

   updateState(e) {

      this.setState({data: e.target.value});

   }

   clearInput() {

      this.setState({data: ''});

      ReactDOM.findDOMNode(this.refs.myInput).focus();

   }

   render() {

      return (

         <div>

            <input value = {this.state.data} onChange = {this.updateState}

               ref = "myInput"></input>

            <button onClick = {this.clearInput}>CLEAR</button>

            <h4>{this.state.data}</h4>

         </div>

      );

   }

}

export default App;

main.js

import React from 'react';

import ReactDOM from 'react-dom';

import App from './App.jsx';

 

ReactDOM.render(<App/>, document.getElementById('app'));

Sau khi nhấp vào nút, đầu vào sẽ được xóa.