Ref được sử dụng để tương tác với các thành phần mà component đó return ra. Các bạn xem ví dụ dưới các ví dụ dưới đây để hiểu rõ.
Simple example¶
Trong ví dụ này, các bạn sẽ tạo 1 component return 1 thẻ input để nhập dữ liệu, và 1 button để khi click vào alert dữ liệu đã nhập.
...
Code Block | ||
---|---|---|
| ||
class App extends React.Component { constructor(props){ super(props); this.layThongtin=this.layThongtin.bind(this); } layThongtin(){ var text=this.refs.myInput.value; alert(text); } render() { return ( <div> <input ref="myInput" type="text"/> <button onClick={this.layThongtin}>click</button> </div> ); } } |
Complex example¶
Trong ví dụ này chúng ta sẽ sử dung refs để xóa dữ liệu trong thẻ input bằng ClearInput function tìm kiếm 1 phần tử có ref=myInput thông ReactDom.findDomNode.
...