1. Trang chủ
  2. » Công Nghệ Thông Tin

Hướng dẫn ReactJS ReactJS tutorial (p10) Bài 10: ReactJS sử dụng Refs

3 152 4

Đang tải... (xem toàn văn)

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 3
Dung lượng 47,39 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

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õ. Using Refs 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.

Trang 1

Bài 10: ReactJS - sử dụng Refs

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õ

Using Refs

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

App.js

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>

);

}

}

Index.js

import React from 'react';

import ReactDOM from 'react-dom';

import App from './App.jsx';

Trang 2

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

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 App.js

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 (

Trang 3

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

Index.js

import React from 'react';

import ReactDOM from 'react-dom';

import App from './App.jsx';

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

Một khi button được nhấn, nội dung input sẽ bị xóa và thẻ input được focus

Ngày đăng: 03/04/2018, 17:32

TỪ KHÓA LIÊN QUAN

TÀI LIỆU CÙNG NGƯỜI DÙNG

TÀI LIỆU LIÊN QUAN

w