Sau khi đã thiết lập xong React Native thì mình biết chắc rằng các bạn đang nóng lòng muốn biết tất cả các kiến thức nhưng chớ có vội. Trước hết, chúng ta phải biết được các yêu cầu cơ bản để giúp bạn không bị bỡ ngỡ và chuẩn bị các kỹ năng cần thiết để có thể bắt tay vào học React Native:

  • Bạn cần có các kiến thức lập trình cơ bản như hàm, đối tượng, mảng, và các lớp.
  • Bạn cần có các kiến thức cơ bản về JavaScript.
  • Đã có kiến thức về HTML và CSS.
  • Cuối cùng, nếu như trước đó bạn đã làm việc với React.js, thì bạn cũng sẽ biết được rất nhiều kiến thức về React Native, và do vậy sẽ tiếp thu dễ dàng hơn rất nhiều.

Sau khi đã biết được chúng ta cần trang bị những gì, chúng ta hãy cùng tìm hiểu về các kiến thức React Native từ cơ bản đến nâng cao:

I.Kiến thức cơ bản

Phần 1: Ứng dụng đầu tiên “Hello World”

Sẽ không thể thiếu được chương trình đầu tiên và cơ bản nhất đối với mọi ngôn ngữ lập trình. Hãy cùng xây dựng ứng dụng React Native đầu tiên trên Windows với vai trò hệ điều hành phát triển và Android là hệ điều hành mục tiêu.

  • Các bước để tạo ứng dụng React Native.
  • Khởi động trình giả lập Android (Android Emulator) và chạy nó.
  • Tạo một thư mục (ReactNative) trên bất kỳ ổ đĩa nào.
  • Mở “Command Prompt” và đến thư mục ReactNative.
  • Viết một lệnh react-native init FirstApp để khởi tạo ứng dụng “FirstApp” của bạn.

1. Đi tới vị trí thư mục “FirstApp” và chạy lệnh react-native run-android. Nó sẽ khởi động máy chủ Node và chạy ứng dụng của bạn trên một trình giả lập thiết bị.

Output:

2. Xem code của ứng dụng React Native

Mở bất kỳ IDE nào có hỗ trợ JavaScript mà bạn thích và mở tệp App.js trong ứng dụng FirstApp.

Dưới đây là code mặc định của ứng dụng React Native đầu tiên.

App.js

import React, {Component} from 'react';  
import {Platform, StyleSheet, Text, View} from 'react-native';  
 
const instructions = Platform.select({  
  ios: 'Press Cmd+R to reload,\n' + 'Cmd+D or shake for dev menu',  
  android:
    'Double tap R on your keyboard to reload,\n' +  
    'Shake or press menu button for dev menu',  
});  
 
type Props = {};  
export default class App extends Component<Props> {  
  render() {  
    return (  
      <View style={styles.container}>
        <Text style={styles.welcome}>Welcome to React Native!</Text>
        <Text style={styles.instructions}>To get started, edit App.js</Text>
        <Text style={styles.instructions}>{instructions}</Text>
      </View>
    );  
  }  
}  
 
const styles = StyleSheet.create({  
  container: {  
    flex: 1,  
    justifyContent: 'center',  
    alignItems: 'center',  
    backgroundColor: '#F5FCFF',  
  },  
  welcome: {  
    fontSize: 20,  
    textAlign: 'center',  
    margin: 10,  
  },  
  instructions: {  
    textAlign: 'center',  
    color: '#333333',  
    marginBottom: 5,  
  },  
});

index.js

/** @format */
 
import {AppRegistry} from 'react-native';  
import App from './App';  
import {name as appName} from './app.json';  
 
AppRegistry.registerComponent(appName, () => App);

3. Tạo một ứng dụng React Native “Hello World” đơn giản

Chúng ta có thể tạo ứng dụng “Hello World” bằng cách biên tập tệp App.js của FirstApp.

Lưu ứng dụng và tải lại bằng cách nhấn đúp phím “R” hoặc dùng tổ hợp phím Ctrl+M (Reload).

App.js

import React, {Component} from 'react';  
import {Platform, StyleSheet, Text, View} from 'react-native';  
 
type Props = {};  
export default class App extends Component<Props> {  
  render() {  
    return (  
      <View>
        <Text>Hello World</Text>
      </View>
    );  
  }  
}

Output:

4. Biên tập ứng dụng React Native “Hello World”

Chúng ta sẽ biên tập ứng dụng React Native “Hello World” bằng StyleSheet.

App.js

import React, {Component} from 'react';  
import {Platform, StyleSheet, Text, View} from 'react-native';  
 
type Props = {};  
export default class App extends Component<Props> {  
  render() {  
    return (  
      <View>
        <Text style={styles.welcome}>Hello World</Text>
      </View>
    );  
  }  
}  
const styles = StyleSheet.create({  
  welcome: {  
    fontSize: 20,  
    textAlign: 'center',  
    margin: 10,  
  }  
}); 

Output:

Giải thích code của React Native Code:

  • import React, {Component} from 'react': import thư viện và các thành phần khác từ react module và chỉ định chúng đến biến React.
  • const instruction: các bộ hiển thị thông báo cụ thể theo từng nền tảng.
  • export default class App extends Component: định nghĩa các lớp mà mở rộng thành phần React. Modifier export default class làm cho lớp trở nên “công khai”. Khối code định nghĩa các thành phần đại diện cho giao diện người dùng.
  • render(): trả về một phần tử React element.
  • return(): trả về kết quả của layout và các thành phần UI.
  • View: một container hỗ trợ các điều chỉnh các tính năng truy cập layout. Đây là một thành phần cơ bản để xây dựng UI.
  • Text: là thành phần React để hiển thị văn bản.
  • style: một property sử dụng để tạo kiểu cho các thành phần bằng StyleSheet.
  • styles: sử dụng để thiết kế riêng từng thành phần.
  • const styles = StyleSheet.create({}): là lớp StyleSheet tạo ra các đối tượng kiểu để điều chỉnh layout và bề ngoài của các thành phần. Nó tương tự như Cascading Style Sheets (CSS) sử dụng trên Web.

Phần 2: View, State và Prop

1. React Native View

View là một thành phần cơ bản của React Native để xây dựng giao diện người dùng (UI). Nó là một container that hỗ tợ layout với flexbox, kiểu, thao tác chạm, và các điều khiển khả năng truy cập. Nó ánh xạ trực tiếp vào view gốc tương tự như bất kì nền tảng nào mà ứng dụng React Native đang hoạt động trên đó. Nó hiển thị các thành phần bất kể với UIView, <div>, android.view, …

Thành phần View có thể được lồng vào nhau, chứa các view khác bên trong nó. Nó có thể chứa từ 0 đến rất nhiều thành phần con của bất kỳ loại nào.

Chú ý: Thành phần View được sử dụng cùng StyleSheet khiến nó rõ ràng và đạt hiệu năng tốt hơn well performed, tuy nhiên, nó cũng hỗ trợ các kiểu inline.

Các Prop của View

onStartShouldSetResponderaccessibilityLabelaccessibilityHinthitSlop
nativeIDonAccessibilityTaponLayoutonMagicTap
onMoveShouldSetResponderonMoveShouldSetResponderCaptureonResponderGrantonResponderMove
onResponderRejectonResponderReleaseonResponderTerminateonResponderTerminationRequest
accessibleonStartShouldSetResponderCapturepointerEventsremoveClippedSubviews
styletestIDaccessibilityComponentTypeaccessibilityLiveRegion
collapsableimportantForAccessibilityneedsOffscreenAlphaCompositingrenderToHardwareTextureAndroid
accessibilityRoleaccessibilityStatesaccessibilityTraitsaccessibilityViewIsModal
accessibilityElementsHiddenaccessibilityIgnoresInvertColorsshouldRasterizeIOS 

Ví dụ về React Native View

Trong ví dụ này, chúng ta sẽ tạo thành phần View chứa 2 hộp màu và và một thành phần văn bản liền kề nhau với các kích thước chiều cao và chiều rộng.

App.js

import React, { Component } from 'react'
import {StyleSheet,View, Text} from 'react-native'
 
export default class SwitchExample extends Component {  
    render() {  
        return (  
            <View style={styles.container}>
                <View style={{backgroundColor: 'blue', flex: 0.3}} />
                <View style={{backgroundColor: 'red', flex: 0.5}} />
                <Text style={{fontSize: 18}}>View Example</Text>
            </View>
        );  
    }  
}  
const styles = StyleSheet.create ({  
     container: {  
         flex: 1,  
         flexDirection: 'row',  
         height: 100,  
         width: "80%",  
         backgroundColor:"#5ead97"
     }  
})

Output:

2. React Na​tive State

Có 2 kiểu dữ liệu đó là state và props trong React Native để điều khiển các thành phần. Các thành phần sử dụng state có thể biến đổi. Chúng có thể được thay đổi sau nếu cần thiết. Các thành phần props là không thể biến đổi và cố định trong toàn bộ thời gian hoạt động.

State thường được khởi chạy trong hàm dựng và sau đó gọi setState khi chúng ta muốn thay đổi nó.

React Native state Ví dụ 1

Trong ví dụ này, Chúng ta tạo một thành phần Text với dữ liệu state. Nội dung của thành phần Text sẽ được cập nhật bằng cách click lên nó. Sự kiện onPress sẽ gọi setState, và nó sẽ cập nhật state của văn bản "myState".

import React, {Component} from 'react';  
import { Text, View } from 'react-native';  
 
export default class App extends Component {  
    state = {  
        myState: 'This is a text component, created using state data. It will change or updated on clicking it.'
    }  
    updateState = () => this.setState({myState: 'The state is updated'})  
    render() {  
        return (  
            <View>
                <Text onPress={this.updateState}> {this.state.myState} </Text>
            </View>
        );  
    }  
}

Output:

React Native state Ví dụ 2

Chúng ta hãy cùng tạo một thành phần khác của dữ liệu state để thay đổi xen kẽ giá trị của Text giữa “Show” và “Hide” để hiển thị và ẩn phần nhập mật khẩu.

Tạo 3 biến state mà sẽ được thay đổi khi click vào thành phần Text được định nghĩa như một state. Click vào thành phần Text component sẽ gọi hàm handleToggle, và state hiện tại của biến Boolean “isPasswordVisible” được chỉ định trong nó. Lúc này, if sẽ kiểm tra giá trị của “isPasswordVisible” và tiến hành tiếp tùy theo kểt quả.

import React, { Component } from 'react';  
import {StyleSheet,Text,View,TextInput,TouchableOpacity} from 'react-native';  
 
export default class App extends Component {  
    state: {  
        password: string,  
        isPasswordVisible: boolean,  
        toggleText: string,  
    }  
    constructor(props: Props) {  
        super(props);  
        this.state = {  
            password: '',  
            isPasswordVisible: true,  
            toggleText: 'Show',  
        };  
    }  
    handleToggle = () => {  
        const { isPasswordVisible } = this.state;  
        if (isPasswordVisible) {  
            this.setState({ isPasswordVisible: false });  
            this.setState({ toggleText: 'Hide' });  
        } else {  
            this.setState({ isPasswordVisible: true });  
            this.setState({ toggleText: 'Show' });  
        }  
    };  
    render() {  
        return (  
            <View style={styles.container}>
                <TextInput
                    secureTextEntry={this.state.isPasswordVisible}
                    style={{ width: 400, height: 50, backgroundColor: '#a7a6a9', color: 'white', fontSize: 20 }}
                />
                <TouchableOpacity onPress={this.handleToggle}>
                    <Text  style={{fontSize: 20}}>{this.state.toggleText}</Text>
                </TouchableOpacity>
            </View>
        );  
    }  
}  
const styles = StyleSheet.create({  
    container: {  
        flex: 1,  
        justifyContent: 'center',  
        alignItems: 'center',  
    }  
});

Output:

3. React Native Props

Các property của thành phần React Native components được gọi đơn giản là props. Trong React Native, các thành phần có thể được tùy chỉnh trong quá trình tạo ra chúng với các tham số khác nhau. Các tham số này chính là các props. Chúng là không thể biến đổi và không thể thay đổi được.

Một ví dụ về props đó là source property nếu thành phần Image điều chỉnh các hình ảnh được hiển thị trên màn hình của thiết bị.

Props mặc định của React Native

import React, { Component } from 'react';  
import {  
  Platform,  
  StyleSheet,  
  Image,  
  Text,  
  View
} from 'react-native';  
 
 
export default class App extends Component<{}> {  
  render() {  
    let imagePath = { uri: 'https://facebook.github.io/react-native/img/header_logo.png'};  
"rel=nofollow"
    return (  
        <View style={styles.container}>
          <Text style={styles.welcome}>Welcome to React Native!</Text>
          <Image source={imagePath} style={{width: 250, height: 250}} />
        </View>
    );  
  }  
}  
 
const styles = StyleSheet.create({  
  container: {  
    flex: 1,  
    justifyContent: 'center',  
    alignItems: 'center',  
    backgroundColor: '#a7a6a9',  
  },  
  welcome: {  
    fontSize: 30,  
    textAlign: 'center',  
    margin: 20,  
  }  
});

Output:

Sử dụng props trong thành phần của riêng bạn

Chúng ta có thể sử dụng props trong các thành phần của riêng mình. Một thành phần có thể được sử dụng ở nhiều nơi trong ứng dụng bằng cách dùng các property hơi khác nhau một chút ở từng nơi. Để cài đặt props vào thành phần, this.props sẽ được thêm vào và sau đó là property.

Ví dụ, một trong những thành phần cơ bản của React Native là Text. Khi chúng ta tạo một thành phần Text, chúng ta có thể dùng một prop “name” là props để điều chỉnh bề ngoài của nó. Chúng ta cũng sẽ áp dụng StyleSheet vào thành phần của chúng ta.

App.js

import React, { Component } from 'react';  
import { StyleSheet, Text, View } from 'react-native';  
 
class ChildClass extends Component {  
  render() {  
    return (  
        <View style={{alignItems: 'center'}}>
          <Text style={styles.welcome}>Hello {this.props.name}!</Text>
        </View>
    );  
  }  
}  
 
export default class ParentsClass extends Component {  
  render() {  
    return (  
        <View style={{alignItems: 'center'}}>
          <ChildClass name='Ashu' />
          <ChildClass name='Aman' />
          <ChildClass name='Max' />
        </View>
    );  
  }  
}  
const styles = StyleSheet.create({  
   welcome: {  
    fontSize: 30,  
  }  
});  
 
// skip this line if using Create React Native App  
//AppRegistry.registerComponent('MyReactNativeApp', () => ParentsClass);

Output:

Phần 3: React Native Style

React Native chỉ sử dụng JavaScript để tạo kiểu cho các thành phần cốt lõi. Chúng ta không cần bất kỳ ngôn ngữ hay cú pháp đặc biệt nào để định nghĩa cho kiểu. Tất cả các thành phần cốt lõi đều sử dụng một prop (property) đó là style. Các tên và giá trị của style names cũng tương tự như CSS của web. Khác biệt duy nhất là cách viết tên liền nhau không dấu, chẳng hạn như fontSize thay vì font-size.

Style prop is đơn giản là một đối tượng JavaScript, là cách đơn giản nhất để tạo kiểu cho code.

Có nhiều cách để thiết kế các thành phần, sử dụng kiểu inline và StyleSheet.create. Khi các thành phần phức tạp hơn ,thì tốt hơn là nên dùng StyleSheet.create để định nghĩa nhiều kiểu ở cùng một nơi.

React Native style Ví dụ 1

Trong ví dụ này, chúng ta sẽ sử dụng cả kiểu inline và StyleSheet.create. Kiểu inline được áp dụng khi các thành phần được tạo.

App.js

import React, { Component } from 'react';  
import { AppRegistry, StyleSheet, Text, View } from 'react-native';  
 
export default class ImplementingStyle extends Component {  
    render() {  
        return (  
            <View>
                <Text style={{ backgroundColor: '#a7a6a9', color: 'yellow', fontSize: 20 }}>this is inline style</Text>
                <Text style={styles.green}>just green</Text>
                <Text style={styles.biggray}>just biggray</Text>
                <Text style={[styles.biggray, styles.green]}>biggray, then green</Text>
                <Text style={[styles.green, styles.biggray]}>green, then biggray</Text>
            </View>
        );  
    }  
}  
const styles = StyleSheet.create({  
    biggray: {  
        color: 'gray',  
        fontWeight: 'bold',  
        fontSize: 30,  
    },  
    green: {  
        color: 'green',  
    },  
});

Output:

React Native style Ví dụ 2

Chúng ta cũng có thể sử dụng các tệp JavaScript bên ngoài để tạo kiểu cho các thành phần. Trong ví dụ này, we chúng ta sẽ tạo tệp JS bên ngoài và import nó vào tệp App.js của chúng ta.

StyleComponent.js

import React, { Component } from 'react'
import { Text, View, StyleSheet } from 'react-native'
 
const StyleComponent = (props) => {  
    return (  
        <View>
            <Text style = {styles.myState}>
                {props.myState}
            </Text>
        </View>
    )  
}  
export default StyleComponent
 
const styles = StyleSheet.create ({  
    myState: {  
        marginTop: 20,  
        textAlign: 'center',  
        color: 'green',  
        fontWeight: 'bold',  
        fontSize: 20
    }  
})

App.js

import React from 'react';  
import { StyleSheet, Text, View } from 'react-native';  
import StyleComponent from './StyleComponent'
 
export default class App extends React.Component {  
    state = {  
        myState: 'This is my state, style through external style'
    }  
    render() {  
        return (  
            <View>
                <StyleComponent myState = {this.state.myState}/>
            </View>
        );  
    }  
}

Output:

Phần 4: Chiều cao và chiều rộng

Chiều cao và chiều rộng quyết định kích cỡ của thành phần trên màn hình. Có 2 cách để đặt chiều cao và chiều rộng của thành phần: Fixed DimensionsFlex Dimensions.

Fixed Dimensions (Chiều không gian cố định)

Sử dụng chiều cao cố định và chiều rộng cố định trong style là cách đơn giản nhất để đặt không gian của thành phần. Các chiều không gian của thành phần React Native là không có đơn vị, và chúng đại diện cho các pixel độc lập với mật độ.

Thiết lập không gian của thành phần với kích cỡ cố định là thông thường và chính xác về kích cỡ, bất kể không gian của màn hình.

import React, { Component } from 'react';  
import { StyleSheet, View } from 'react-native';  
 
export default class HeightWidth extends Component {  
    render() {  
        return (  
            <View>
                <View style={styles.powderblue} />
                <View style={styles.skyblue} />
                <View style={styles.steelblue} />
            </View>
        );  
    }  
}  
const styles = StyleSheet.create({  
    powderblue:{  
        width: 100, height: 100, backgroundColor: 'powderblue'
    },  
    skyblue:{  
        width: 200, height: 200, backgroundColor: 'skyblue'
    },  
    steelblue:{  
        height: 300, backgroundColor: 'steelblue'
    },  
})

Output:

Flex Dimensions (Chiều không gian linh hoạt)

Flex property tạo kiểu cho các thành phần để có thể mở rộng hoặc co lại một cách linh động tùy theo không gian đang có. Đặt flex: 1 sẽ lấp đầy các khoảng không gian trống bằng cả thành phần, và được chia đều giữa các thành phần có cùng thành phần cha. Giá trị flex càng cao, thì thành phần đó sẽ chiếm tỉ lệ trong không gia cao hơn so với các thành phần họ hàng của nó.

import React, { Component } from 'react';  
import { StyleSheet, View } from 'react-native';  
 
export default class HeightWidth extends Component {  
    render() {  
        return (  
            <View style={styles.container}>
                <View style={styles.powderblue} />
                <View style={styles.skyblue} />
                <View style={styles.steelblue} />
            </View>
        );  
    }  
}  
const styles = StyleSheet.create({  
    container:{  
      flex:1
    },  
    powderblue:{  
        flex:1,  
        backgroundColor: 'powderblue',  
    },  
    skyblue:{  
        flex:2,  
        backgroundColor: 'skyblue',  
    },  
    steelblue:{  
        flex:3,  
        backgroundColor: 'steelblue',  
    },  
})

Output:

Phần 5: Các nút React Native (Buttons)

Phần lớn người dùng tương tác với các thiết bị di động qua cảm ứng chạm. Có một tập hợp các cử chỉ với nó, chẳng hạn như gõ vào nút, phóng to bản đồ, cuộn một danh sách, … Nút là một trong những thành phần để thao tác với các click.

Nút React Native là một thành phần cơ bản hoạt động bằng cách click lên nó. Nó import lớp Button của react-native.

Các Prop của Button

PropKiểuBắt buộcMô tả
onPressfunctionGọi handler khi người dùng click vào nút.
titlestringHiển thị văn bản bên trong nút.
accessibilityLabelstringKhôngHiển thị văn bản cho các chức năng truy cập dành cho người khiếm thị.
colorColorKhôngĐặt màu nền của nút Android hoặc màu của văn bản iOS.
disabledboolKhôngVô hiệu hóa tất cả các tương tác của thành phần, nếu là true.
textIDstringKhôngSử dụng để định vị view trong kiểm thử đầu-cuối.
hasTVPreferredFocusboolKhôngHiệu ứng TV preffered focus, chỉ hoạt động trên Apple TV.

Ví dụ về React Native Button

Trong ví dụ này, chúng ta sẽ làm việc với thành phần button.Thành phần React Native Button import lớp Button của thư viện react-native. Nó có một vài props như title, onPress, accessibilityLabel, v..v… như đã được nhắc đến phía trên.

Trong code dưới đây title prop sẽ đặt title của nút, onPress prop gọi hàm mention và thực hiện một sự kiện. Color prop sẽ đặt màu của nút, và disabled={true} sẽ vô hiệu hóa nút.

import React, { Component } from 'react';  
import { Alert, AppRegistry, Button, StyleSheet, View } from 'react-native';  
 
export default class ButtonBasics extends Component {  
    onPressButton() {  
        Alert.alert('You clicked the button!')  
    }  
 
    render() {  
        return (  
            <View style={styles.container}>
                <View style={styles.buttonContainer}>
                    <Button
                        onPress={this.onPressButton}
                        title="Press Me"
                    />
                </View>
                <View style={styles.buttonContainer}>
                    <Button
                        onPress={this.onPressButton}
                        title="Press Me"
                        color="#009933"
                    />
                </View>
                <View style={styles.multiButtonContainer}>
                    <Button
                        onPress={this.onPressButton}
                        title="A disabled button"
                        disabled={true}
                    />
                    <Button
                        onPress={this.onPressButton}
                        title="OK!"
                        color="#009933"
                    />
                </View>
            </View>
        );  
    }  
}  
 
const styles = StyleSheet.create({  
    container: {  
        flex: 1,  
        justifyContent: 'center',  
    },  
    buttonContainer: {  
        margin: 20
    },  
    multiButtonContainer: {  
        margin: 20,  
        flexDirection: 'row',  
        justifyContent: 'space-between'
    }  
})  

Output:

Phần 6: Layout và Flexbox

React Native Flexbox là một thuật toán để chỉ rõ layout thành phần con của một thành phần cha. Nó sẽ đưa ra layout đồng nhất trên các kích cỡ màn hình khác nhau.

Property của Flexbox

Flexbox cung cấp 3 property chính để đạt được layout mong muốn. 3 property này bao gồm: flexDirection, justifyContent, và alignItems.

PropertyCác giá trịMô tả
flexDirection'column', 'row'Sử dụng để sắp xếp các phần tử thẳng hàng theo chiều dọc hoặc chiều ngang.
justifyContent'center', 'flex-start', 'flex-end', 'space-around', 'space-between'Sử dụng để phân bổ các phần tử bên trong container.
alignItems'center', 'flex-start', 'flex-end', 'stretched'Sử dụn để phân bổ các thành phần bên trong container với một trục thứ 2 (đối lập với flexDirection).

React Native Flex Direction

flexDirection thêm kiểu vào các thành phần trên một trục chính trong layout của nó. Nó có một property hàng và cột để sắp xếp các thành phần con lần lượt theo chiều ngang và chiều dọc. default flexDirection là một cột.

import React, { Component } from 'react';  
import { StyleSheet,View } from 'react-native';  
 
export default class FlexDirectionBasics extends Component {  
    render() {  
        return (  
            <View style={styles.container}>
                <View style={styles.powderblue} />
                <View style={styles.skyblue} />
                <View style={styles.steelblue} />
            </View>
        );  
    }  
}  
const styles = StyleSheet.create({  
    container:{  
        flex: 1,  
        flexDirection: 'row',// set elements horizontally, try column.  
    },  
    powderblue:{  
        width: 60,  
        height: 60,  
        backgroundColor: 'powderblue',  
    },  
    skyblue:{  
        width: 60,  
        height: 60,  
        backgroundColor: 'skyblue',  
    },  
    steelblue:{  
        width: 60,  
        height: 60,  
        backgroundColor: 'steelblue',  
    }  
})

Output:

React Native Justify Content

justifyContent quyết định sự phân bổ các thành phần con theo trục chính. Thành phần con được phân bố ở đầu, cuối, giữa, hay được căn đều.

import React, { Component } from 'react';  
import { StyleSheet,View } from 'react-native';  
 
export default class JustifyContentBasics extends Component {  
    render() {  
        return (  
            <View style={styles.container}>
                <View style={styles.powderblue} />
                <View style={styles.skyblue} />
                <View style={styles.steelblue} />
            </View>
        );  
    }  
}  
const styles = StyleSheet.create({  
    container:{  
        flex: 1,  
        flexDirection: 'column', // set elements horizontally`.  
        justifyContent: 'center',  
 
    },  
    powderblue:{  
        width: 60,  
        height: 60,  
        backgroundColor: 'powderblue'
    },  
    skyblue:{  
        width: 60,  
        height: 60,  
        backgroundColor: 'skyblue',  
    },  
    steelblue:{  
        width: 60,  
        height: 60,  
        backgroundColor: 'steelblue',  
    }  
})

Output:

React Native Align Items

alignItems quyết định việc sắp xếp các thành phần con theo một trục phụ thứ 2. Nếu trục chính là một cột, thì trục phụ sẽ là một hàng và ngược lại. Sử dụng alignItems, các thành phần con sẽ được xếp thẳng hàng ở đầu, cuối, giữa, hoặc được kéo dãn ra.

import React, { Component } from 'react';  
import { StyleSheet,View } from 'react-native';  
 
export default class AlignItemsBasics extends Component {  
    render() {  
        return (  
            <View style={styles.container}>
                <View style={styles.powderblue} />
                <View style={styles.skyblue} />
                <View style={styles.steelblue} />
            </View>
        );  
    }  
}  
const styles = StyleSheet.create({  
    container:{  
        flex: 1,  
        flexDirection: 'column', // set elements horizontally`.  
        justifyContent: 'center',  
        alignItems: 'stretch',  
    },  
    powderblue:{  
        width: 60,  
        height: 60,  
        backgroundColor: 'powderblue'
    },  
    skyblue:{  
        width: 60,  
        height: 60,  
        backgroundColor: 'skyblue',  
    },  
    steelblue:{  
        /*width: 60,*/
        height: 60,  
        backgroundColor: 'steelblue',  
    }  
})

Output:

Chú ý: Kéo dãn sẽ không có tác dụng nếu thành phần con có một chiều không gian cố định theo trục phụ. Trong ví dụ trên, alignItems: stretch sẽ không có tác dụng nếu chúng ta không loại bỏ width: 50.

Phần 7: Đặt vị trí phần tử với Flex

Trong bài trước về Layout và Flexbox, chúng ta đã thảo luận về Flexbox và các property của nó. Trong bài này, chúng ta sẽ đặt vị trí của các phần tử với Flex.

Ví dụ 1

Tạo một thành phần View và đặt 2 phần tử TextInput và Button. Thành phần View với flex property (1) sẽ chiếm hết không gian của thiết bị. Phần tử TextInput và Button được đặt ở default flex axis (như một cột).

import React, { Component } from "react";  
import { StyleSheet, TextInput, View , Button } from "react-native";  
 
export default class App extends Component {  
    state = {  
        placeName: "",  
        places: []  
    };  
 
    placeNameChangedHandler = val => {  
        this.setState({  
            placeName: val
        });  
    };  
 
    placeSubmitHandler = () => {  
        alert("button clicked")  
    };  
 
    render() {  
        return (  
            <View style={styles.container}>
                <TextInput
                        placeholder="An awesome place"
                        onChangeText={this.placeNameChangedHandler}
                        style={styles.placeInput}
                />
                <Button
                        title="Button"
                        onPress={this.placeSubmitHandler}
                />
            </View>
        );  
    }  
}  
 
const styles = StyleSheet.create({  
    container: {  
        flex: 1,  
        padding: 26,  
        backgroundColor: "#fff",  
        justifyContent: "flex-start"
    }  
});

Output:

Ví dụ 2

Trong ví dụ này chúng ta sẽ đặt phần tử Button ở phía bên phải của phần tử TextInput. Thêm một thành phần con View vào trong thành phần cha View với flex: 1flexDirtection : "row". Đặt flex: 1 để View bên trong chiếm toàn bộ không gian từ trên xuống dưới và từ trái sang phải. flexDirtection: "row" đặt các phần tử theo hàng trong thành phần View ở phía bên trong.

import React, { Component } from "react";  
import { StyleSheet, View, TextInput, Button } from "react-native";  
 
export default class App extends Component {  
    state = {  
        placeName: "",  
        places: []  
    };  
 
    placeNameChangedHandler = val => {  
        this.setState({  
            placeName: val
        });  
    };  
 
    placeSubmitHandler = () => {  
        alert("button clicked")  
    };  
 
    render() {  
        return (  
            <View style={styles.container}>
                <View style={styles.innerContainer}>
                    <TextInput
                            placeholder="An awesome place"
                            onChangeText={this.placeNameChangedHandler}
                    />
                    <Button
                            title="Button"
                            onPress={this.placeSubmitHandler}
                    />
                </View>
            </View>
        );  
    }  
}  
 
const styles = StyleSheet.create({  
    container: {  
        flex: 1,  
        padding: 26,  
        backgroundColor: "#fff",  
        justifyContent: "flex-start"
    },  
    innerContainer:{  
        flex: 1,  
        flexDirection: "row"
    }  
});

Output:

flex:1 để View phía bên trong chiếm toàn bộ không gian trông sẽ không đẹp mắt như để TextInput và Button chiếm toàn bộ không gian từ trên xuống dưới.

Ví dụ 3

Trong ví dụ này, chúng ta sẽ loại bỏ flex property của View phía bên trong và thêm width: 100%. Loại bỏ flex từ View phía bên trong sẽ đặt chiều không gian mặc định của các phần tử. Đặt width :"100%" để View phía bên trong chiếm trọn chiều ngang và chiều cao mặc định của các phần tử.

import React, { Component } from "react";  
import { StyleSheet, View, TextInput, Button } from "react-native";  
 
export default class App extends Component {  
    state = {  
        placeName: "",  
        places: []  
    };  
 
    placeNameChangedHandler = val => {  
        this.setState({  
            placeName: val
        });  
    };  
 
    placeSubmitHandler = () => {  
        alert("button clicked")  
    };  
 
    render() {  
        return (  
            <View style={styles.container}>
                <View style={styles.innerContainer}>
                    <TextInput
                            placeholder="An awesome place"
                            onChangeText={this.placeNameChangedHandler}
                            style={styles.textStyle}
                    />
                    <Button
                            title="Button"
                            onPress={this.placeSubmitHandler}
                    />
                </View>
            </View>
        );  
    }  
}  
 
const styles = StyleSheet.create({  
    container: {  
        flex: 1,  
        padding: 26,  
        backgroundColor: "#fff",  
        justifyContent: "flex-start"
    },  
    innerContainer:{  
       // flex: 1,  
        width: "100%",  
        flexDirection: "row",  
        justifyContent: "space-between",  
        alignItems: "center"
    },  
    textStyle:{  
        width: "70%",  
        backgroundColor: "gray",  
    },  
    buttonStyle:{  
        width: "30%",  
    }  
});

Output:

Phần 8: React Native ScrollView

ScrollView là một container thông thường có thể cuộn được, và có thể cuộn được nhiều thành phần con và view bên trong nó. Trong ScrollView, chúng ta có thể cuộn các thành phần theo chiều dọc and và chiều ngang. Mặc định, ScrollView container cuộn các thành phần và view của nó theo chiều dọc Để cuộn các thành phần theo chiều ngang, nó sử dụng các prop horizontal: true (mặc định, horizontal: false).

Các Props của ScrollView

alwaysBounceVerticalonScrollhorizontal 
contentContainerStylescrollEnabledbouncesZoomzoomScale
onScrollBeginDragonContentSizeChangemaximumZoomScaleminimumZoomScale
onScrollBeginDragonContentSizeChangemaximumZoomScaleminimumZoomScale
onScrollEndDragcenterContentcontentInsetrefreshControl
pagingEnabledscrollsToTopsnapToAlignmentshowsHorizontalScrollIndicator
snapToStartsnapToEndindicatorStyleshowsHorizontalScrollIndicator

Ví dụ về React Native ScrollView

Trong ví dụ này, Chúng ta sẽ tạo ScrollView theo chiều dọc sử dụng các thành phần Text và Button.

App.js

import React, { Component } from 'react';  
import { AppRegistry, ScrollView, Image, Text, Button, StyleSheet } from 'react-native';  
 
export default class ScrolledViewExample extends Component {  
    onPressButton() {  
        alert('You clicked the button!')  
    }  
 
    render() {  
        return (  
            <ScrollView >
                <Text style={{fontSize:20}}>Scroll me plz</Text>
                <Button title={'Button 1'} onPress={this.onPressButton} />
                <Text style={{fontSize:20}}>React Native Example of ScrollView</Text>
                <Button title={'Button 2'} onPress={this.onPressButton}/>
                <Text style={{fontSize:20}}>React Native ScrollView Example</Text>
                <Button title={'Button 3'} onPress={this.onPressButton}/>
                <Text style={{fontSize:20}}>If you like</Text>
                <Button title={'Button 4'} onPress={this.onPressButton}/>
                <Text style={{fontSize:20}}>Scrolling down</Text>
                <Button title={'Button 5'} onPress={this.onPressButton}/>
                <Text style={{fontSize:20}}>Scrolling down</Text>
                <Button title={'Button 6'} onPress={this.onPressButton}/>
                <Text style={{fontSize:20}}>What's the best</Text>
                <Button title={'Button 7'} onPress={this.onPressButton}/>
                <Text style={{fontSize:20}}>What's the best</Text>
                <Button title={'Button 8'} onPress={this.onPressButton}/>
                <Text style={{fontSize:20}}>Framework around?</Text>
                <Button title={'Button 9'} onPress={this.onPressButton}/>
                <Text style={{fontSize:20}}>Framework around?</Text>
                <Button title={'Button 10'} onPress={this.onPressButton}/>
                <Text style={{fontSize:20}}>React Native</Text>
                <Button title={'Button 11'} onPress={this.onPressButton}/>
                <Text style={{fontSize:20}}>Scroll me plz</Text>
                <Button title={'Button 12'} onPress={this.onPressButton} />
                <Text style={{fontSize:20}}>Scroll me plz</Text>
                <Button title={'Button 13'} onPress={this.onPressButton}/>
                <Text style={{fontSize:20}}>If you like</Text>
                <Button title={'Button 14'} onPress={this.onPressButton}/>
                <Text style={{fontSize:20}}>If you like</Text>
                <Button title={'Button 15'} onPress={this.onPressButton}/>
                <Text style={{fontSize:20}}>Scrolling down</Text>
                <Button title={'Button 16'} onPress={this.onPressButton}/>
            </ScrollView>
        );  
    }  
}  
// skip this line if you are using Create React Native App  
AppRegistry.registerComponent('AwesomeProject', () => ScrolledViewExample);

Output:

Ví dụ về React Native ScrollView theo chiều ngang

ScrollView theo chiều ngang cuộn các thành phần và view từ trái sang phải. Nó sẽ được cài đặt bằng cách đặt cách đặt giá trị của các props horizontal thành true (horizontal={true}).

App.js

import React, { Component } from 'react';  
import { AppRegistry, ScrollView, View, Image, Text, Button, StyleSheet } from 'react-native';  
 
export default class ScrolledViewExample extends Component {  
    onPressButton() {  
        alert('You clicked the button!')  
    }  
 
    render() {  
        return (  
            <ScrollView  horizontal={true} style={styles.container}>
                <Text style={{fontSize:22, padding: 10}}>Horizontal ScrollView</Text>
                <View style={[{ width: 220,height: 70,padding: 10 }]}>
                    <Button
                        onPress={this.onPressButton}
                        title="Button 1"
                        color="#FF3D00"
                    />
                </View>
                <Text style={{fontSize:22, padding: 10}}>javatpoint</Text>
                <View style={[{ width: 220,height: 70,padding: 10 }]}>
                    <Button
                        onPress={this.onPressButton}
                        title="Button 2"
                        color="#3D00FF"
                    />
                </View>
                <Text style={{fontSize:22, padding: 10}}>React Native ScrollView Example</Text>
                <View style={[{ width: 220,height: 70,padding: 10 }]}>
                    <Button
                        onPress={this.onPressButton}
                        title="Button 3"
                        color="#FFFF3D"
                    />
                </View>
                <Text style={{fontSize:22, padding: 10}}>If you like</Text>
                <View style={[{ width: 220,height: 70,padding: 10 }]}>
                    <Button
                        onPress={this.onPressButton}
                        title="Button 4"
                        color="#FF3DFF"
                    />
                </View>
                <Text style={{fontSize:22, padding: 10}}>Scrolling horizontal</Text>
                <View style={[{ width: 220,height: 70,padding: 10 }]}>
                    <Button
                        onPress={this.onPressButton}
                        title="Button 5"
                        color="#3DFF00"
                    />
                </View>
            </ScrollView>
        );  
    }  
}  
const styles = StyleSheet.create({  
    container:{  
        flex: 1,  
    },  
/*    buttonStyle:{
        height: 50,
        width: 70,
    }*/
})  
// skip this line if you are using Create React Native App  
AppRegistry.registerComponent('AwesomeProject', () => ScrolledViewExample);

Output:

Phần 9: React Native List

1. React Native FlatList

Thành phần FlatList hiển thị các dữ liệu có cấu trúc tương tự nhau trong một danh sách có thể cuộn được. Nó hoạt động tốt với các danh sách dữ liệu lớn khi mà số item trong danh sách có thể thay đổi theo thời gian. FlatList chỉ cho thấy các thành phần được render đang được hiển thị trên màn hình, không phải tất cả các phần tử trong danh sách cùng một lúc.

Thành phần FlatList phải có 2 props: datarenderItem.

data là nguồn của phần tử cho danh sách, và renderItem lấy một item từ nguồn và trả về một thành phần đã được định dạng để render.

Để cài đặt thành phần FlatList, chúng ta cần phải import FlatList từ thư viện 'react-native'.

Ví dụ về React Native FlatList

Chúng ra, chúng ta sẽ cung cấp các phần tử đã được hardcode cho data prop. Mỗi phần tử trong các data props được render như một thành phần Text.

ItemSeparatorComponent prop của FlatList được dùng để đặt dấu ngăn cách giữa các phần tử trong danh sách. Để thực hiện sự kiện trên các item trong danh sách, chúng ta sử dụng onPress prop đến Text.

import React, { Component } from 'react';  
import { AppRegistry, FlatList,  
    StyleSheet, Text, View,Alert } from 'react-native';  
 
export default class FlatListBasics extends Component {  
 
    renderSeparator = () => {  
        return (  
            <View
                style={{  
                    height: 1,  
                    width: "100%",  
                    backgroundColor: "#000",  
                }}
            />
        );  
    };  
    //handling onPress action  
    getListViewItem = (item) => {  
        Alert.alert(item.key);  
    }  
 
    render() {  
        return (  
            <View style={styles.container}>
                <FlatList
                    data={[  
                        {key: 'Android'},{key: 'iOS'}, {key: 'Java'},{key: 'Swift'},  
                        {key: 'Php'},{key: 'Hadoop'},{key: 'Sap'},  
                        {key: 'Python'},{key: 'Ajax'}, {key: 'C++'},  
                        {key: 'Ruby'},{key: 'Rails'},{key: '.Net'},  
                        {key: 'Perl'},{key: 'Sap'},{key: 'Python'},  
                        {key: 'Ajax'}, {key: 'C++'},{key: 'Ruby'},  
                        {key: 'Rails'},{key: '.Net'},{key: 'Perl'}  
                    ]}
                    renderItem={({item}) =>
                        <Text style={styles.item}
                              onPress={this.getListViewItem.bind(this, item)}>{item.key}</Text>}
                    ItemSeparatorComponent={this.renderSeparator}
                />
            </View>
        );  
    }  
}  
 
const styles = StyleSheet.create({  
    container: {  
        flex: 1,  
    },  
    item: {  
        padding: 10,  
        fontSize: 18,  
        height: 44,  
    },  
})  
 
 
AppRegistry.registerComponent('AwesomeProject', () => FlatListBasics);

Output:

2. React Native SectionList

Thành phần React Native SectionList là một thành phần list view đặt các danh sách của dữ liệu thành các phần logic nhỏ hơn. Các phần dữ liệu đã được chia nhỏ có thể được cài đặt bằng cách sử dụng section header prop renderSectionHeader của nó.

Để cài đặt thành phần SectionList component, chúng ta cần phải import SectionList từ thư viện 'react-native'.

Các props của SectionList

sectionsrenderIteminitialNumToRenderkeyExtractor
renderSectionHeaderrenderSectionFooteronRefreshinverted
extraDataonEndReachedkeyExtractorlegacyImplementation
onViewableItemsChangedrefreshingremoveClippedSubviewsListHeaderComponent
SectionSeparatorComponentstickySectionHeadersEnabledonEndReachedThresholdListEmptyComponent

Ví dụ về React Native SectionList

Trong ví dụ này, chúng ta sẽ tạo một SectionList với title và dữ liệu. sections prop được sử dụng để tạo danh sách của các giá trị của title and dữ liệu. renderSectionHeader hiển thị phần tiêu đề của list view.

import React, { Component } from 'react';  
import { AppRegistry, SectionList, StyleSheet, Text, View } from 'react-native';  
 
export default class SectionListBasics extends Component {  
    render() {  
        return (  
            <View style={styles.container}>
                <SectionList
                    sections={[  
                        {title: 'A', data: ['ALTERED','ABBY','ACTION U.S.A.','AMUCK','ANGUISH']},  
                        {title: 'B', data: ['BEST MEN','BEYOND JUSTICE','BLACK GUNN','BLOOD RANCH','BEASTIES']},  
                        {title: 'C', data: ['CARTEL', 'CASTLE OF EVIL', 'CHANCE', 'COP GAME', 'CROSS FIRE',]},  
                    ]}
                    renderItem={({item}) => <Text style={styles.item}>{item}</Text>}
                    renderSectionHeader={({section}) => <Text style={styles.sectionHeader}>{section.title}</Text>}
                    keyExtractor={(item, index) => index}
                />
            </View>
        );  
    }  
}  
 
const styles = StyleSheet.create({  
    container: {  
        flex: 1,  
        backgroundColor: "#5ead97"
    },  
    sectionHeader: {  
        paddingTop: 2,  
        paddingLeft: 10,  
        paddingRight: 10,  
        paddingBottom: 2,  
        fontSize: 22,  
        fontWeight: 'bold',  
        color: "#fff",  
        backgroundColor: '#8fb1aa',  
    },  
    item: {  
        padding: 10,  
        fontSize: 18,  
        height: 44,  
    }  
})  
 
// skip this line if using Create React Native App  
AppRegistry.registerComponent('AwesomeProject', () => SectionListBasics);

Output:

Adding Separator in SectionList

ItemSeparatorComponent thêm dấu phân cách giữa các danh sách data . Để sử dụng phần hỗ trợ này, hãy gọi một renderSeparatormethod, trong đó chúng ta thêm một thành phần View làm dấu phân cách.

renderSeparator = () => {  
    return (  
        <View
            style={{  
                height: 1,  
                width: "100%",  
                backgroundColor: "#000",  
            }}
        />
    );  
};

ItemSeparatorComponent={this.renderSeparator}

Performing action on SectionList items

Để thực hiện một hành động khi nhấp (nhấn) vào mục danh sách, chúng ta sử dụng một phần mềm hỗ trợ onPress. Hỗ trợ onPress và xử lý sự kiện trong phương thức getListViewItem khác.

//handling onPress action  
getListViewItem = (item) => {  
    alert(item);  
}  


renderItem={({item}) => <Text style={styles.item}
onPress={this.getListViewItem.bind(this, item)}>{item}</Text>}

Output:

Phần 10: React Native Touchables

Các thành phần Touchable cung cấp khả năng thực hiện các chức năng cảm ứng chạm. Thành phần touchable có thể được cài đặt để thay thế cho các nút cơ bản nếu chúng không phù hợp với ứng dụng của bạn. Sử dụng các thành phần này thì bạn có thể xây dựng nút riêng của mình. Gõ vào các thành phần này, bạn có thể hiển thị các phản hồi.

Các thành phần touchables không cung cấp bất kỳ kiểu mặc định nào, vì vậy bạn sẽ phải tự tạo kiểu để trình bày trong ứng dụng.

Các kiểu thành phần Touchable

Có 4 thành phần touchable được cung cấp bởi React Native. Lựa chọn các thành phần này tùy theo kiểu phản hồi mà bạn muốn cung cấp:

  • TouchableHighlight
  • TouchableNativeFeedback
  • TouchableOpacity
  • TouchableWithoutFeedback

React Native TouchableHighlight

TouchableHighlight có thể đước sử dụng ở các nút hoặc link trên web. Nền của thành phần này sẽ tối đi nếu bạn nhấn vào nó.

Props

PropsKiểuBắt buộcNền tảngMô tả
activeOpacitynumberKhông Quyết định độ mờ của wrapped view khi được chạm vào.
onHideUnderlayfunctionKhông Gọi ngay lập tức khi lớp dưới bị ẩn đi.
onShowUnderlayfunctionKhông Gọi ngay lập tức khi lớp dưới được hiện ra.
styleView.styleKhông  
underlayColorcolorKhông Hiển thị màu lớp dưới khi kích hoạt chạm.
hasTVPreferredFocusboolKhôngiOSHiệu ứng TV preferred focus, chỉ hoạt động với iOS.
tvParallaxPropertiesobjectKhôngiOSLà một đối tượng với các property điều kiển các hiệu ứng parallax của Apple TV.

React Native TouchableNativeFeedback

TouchableNativeFeedback khiến một view phản hồi đúng khi chạm vào. Thành phần này chỉ hoạt động với hệ điều hành Android. Nó sử dụng native state drawable để hiển thị phản hồi chạm.

Nó chỉ hỗ trợ một lần View đơn nhất như một node con. Nó được cài đặt bằng cách thay thế View với một lần RCTView node khác.

Props

PropsKiểuBắt buộcMô tả
backgroundbackgroundPropTypenoQuyết định background drawable được hiển thị là một phản hồi.
useForegroundboolnoTạo hiệu ứng sóng cho phần nổi của view, thay vì phần nền.

React Native TouchableOpacity

TouchableOpacity wrapper được dùng để giảm độ mờ của nút. Nó cho phép có thể thấy được hình nền khi nhấn xuống. Độ mờ của nút được kiểm soát bằng cách gói thành phần con trong một Animation.

Props

PropsKiểuBắt buộcNền tảngMô tả
activeOpacitynumberKhông Quyết định độ mờ của wrapped view khi được chạm vào.
tvParallaxPropertiesobjectKhôngiOSLà một đối tượng với property được sử dụng để kiểm soát các hiệu ứng parallax của Apple TV.
hasTVPreferredFocusboolKhôngiOSHiệu ứng TV preferred focus, chỉ hoạt động với Apple TV.

Các phương thức

Phương thứcMô tả
setOpacityTo()Tạo hoạt ảnh cho touchable đến một độ mờ mới.

React Native TouchableWithoutFeedback

TouchableWithoutFeedback sử dụng khi người dùng muốn thao tác với chức năng chạm nhưng không muốn hiển thị phản hồi.

Props

PropsKiểuBắt buộcMô tả
hitSlopobjectKhôngĐịnh nghĩa vùng bạn có thể chạm được là bao xa kể từ nút.
onAccessibilityTapfunctionKhôngNếu accessible được đặt là true, hệ thống sẽ khởi động chức năng khi người dùng thực hiện các cử chỉ tiện ích truy cập.
accessibilityHintstringKhôngGiúp người dùng hiểu điều gì sẽ xảy ra khi họ thực hiện hành động trên phần tử tiện ích truy cập.
accessibilityLabelnodeKhôngĐè lên phần văn bản, mà sẽ được đọc bởi trình đọc màn hình khi người dùng tương tác với phần tử.
delayLongPressnumberKhôngHoãn cuộc gọi onPressIn  của onLongPress trong khoảng milli-giây.

Đôi khi người dùng nhấn vào view và giữ trong một khoảng thời gian. Việc nhấn giữ sẽ được xử lý bởi một hàm sử dụng onLongPress props của bất kỳ các thành phần “Touchable” nào ở trên.

Ví dụ về React Native Touchables

import React, { Component } from 'react';  
import { Alert,Platform,StyleSheet,Text,TouchableHighlight,TouchableOpacity,  
    TouchableNativeFeedback,TouchableWithoutFeedback, View } from 'react-native';  
 
export default class Touchables extends Component {  
    _onPressButton() {  
        Alert.alert('You tapped the button!')  
    }  
 
    _onLongPressButton() {  
        Alert.alert('You long-pressed the button!')  
    }  
 
 
    render() {  
        return (  
            <View style={styles.container}>
                <TouchableHighlight onPress={this._onPressButton} underlayColor="white">
                    <View style={styles.button}>
                        <Text style={styles.buttonText}>TouchableHighlight</Text>
                    </View>
                </TouchableHighlight>
                <TouchableOpacity onPress={this._onPressButton}>
                    <View style={styles.button}>
                        <Text style={styles.buttonText}>TouchableOpacity</Text>
                    </View>
                </TouchableOpacity>
                <TouchableNativeFeedback
                    onPress={this._onPressButton}
                    background={Platform.OS === 'android' ? TouchableNativeFeedback.SelectableBackground() : ''}>
                    <View style={styles.button}>
                        <Text style={styles.buttonText}>TouchableNativeFeedback</Text>
                    </View>
                </TouchableNativeFeedback>
                <TouchableWithoutFeedback
                    onPress={this._onPressButton}
                >
                    <View style={styles.button}>
                        <Text style={styles.buttonText}>TouchableWithoutFeedback</Text>
                    </View>
                </TouchableWithoutFeedback>
                <TouchableHighlight onPress={this._onPressButton} onLongPress={this._onLongPressButton} underlayColor="white">
                    <View style={styles.button}>
                        <Text style={styles.buttonText}>Touchable with Long Press</Text>
                    </View>
                </TouchableHighlight>
            </View>
        );  
    }  
}  
 
const styles = StyleSheet.create({  
    container: {  
        paddingTop: 60,  
        alignItems: 'center'
    },  
    button: {  
        marginBottom: 30,  
        width: 260,  
        alignItems: 'center',  
        backgroundColor: '#5ead97'
    },  
    buttonText: {  
        padding: 20,  
        color: 'white',  
        fontSize: 18
    }  
});  

Output:

Phần 11: React Native Text Input

TextInput là một thành phần cơ bản để nhập văn bản. Nó có một vài prop để tùy chỉnh các chức năng khác nhau, chẳng hạn như onChangeText lấy một hàm function và gọi nó bất cứ khi nào văn bản thay đổi. onSubmitEditing lấy một hàm và gọi nó bất cứ khi nào một văn bản được gửi đi.

Có mộ vài việc mà bạn có thể làm với text input, chẳng hạn như xác thực văn bản bên trong khi người nhập gõ vào.

React Native TextInput Ví dụ 1

Trong ví dụ này, chúng ta tạo một TextInput và thực hiện một hành động onChangeText. Bất cứ lúc nào văn bản thay đổi, nó sẽ gọi setState và kiểm tra điều kiện của một split. Nếu input text tìm thấy ''space, it displays'' trong văn bản. Văn bản sẽ được đặt vào một state mà sẽ thay đổi liên tục.

import React, { Component } from 'react';  
import { AppRegistry, Text, TextInput, View } from 'react-native';  
 
export default class PizzaTranslator extends Component {  
    constructor(props) {  
        super(props);  
        this.state = {text: ''};  
    }  
 
    render() {  
        return (  
            <View style={{padding: 10}}>
                <TextInput
                    style={{height: 40,backgroundColor: 'azure', fontSize: 20}}
                    placeholder="Type here to translate!"
                    onChangeText={(text) => this.setState({text})}
                />
                <Text style={{padding: 100, fontSize: 50}}>
                    {this.state.text.split(' ').map((word) => word && '🍕').join(' ')}
                </Text>*  
            </View>
        );  
    }  
}

Output:

Các property của TextInput

allowFontScalingautoCapitalizeautoCorrectautoFocus
blurOnSubmitcaretHiddenclearButtonModeclearTextOnFocus
contextMenuHiddendataDetectorTypesdefaultValuedisableFullscreenUI
editableenablesReturnKeyAutomaticallyinlineImageLeftinlineImagePadding
keyboardAppearancekeyboardTypemaxLengthmultiline
numberOfLinesonBluronChangeonChangeText
onContentSizeChangeonEndEditingonFocusonKeyPress
onLayoutonScrollonSelectionChangeonSubmitEditing
placeholderplaceholderTextColorreturnKeyLabelreturnKeyType
scrollEnabledsecureTextEntryselectionselectionColor
selectionColorselectionStateselectTextOnFocusspellCheck
textContentTypestyletextBreakStrategyunderlineColorAndroid

Phương thức .focus().blur() được phô ra từ các phần tử gốc. Các phương thức này sẽ tập trung vào hoặc làm mờ TextInput theo như đã lập trình sẵn.

Multiline TextInput

multiline prop cung cấp cơ sở để nhập nhiều dòng văn bản. Một số prop của TextInput chỉ tương thích với multiline, chẳng hạn như, multiline={true/false}. Property borderButtomColor sẽ không hoạt động nếu multiline = false.

React Native TextInput Ví dụ 2

import React, { Component } from 'react';  
import { AppRegistry, View, TextInput } from 'react-native';  
 
class UselessTextInput extends Component {  
    render() {  
        return (  
            <TextInput
                {...this.props} // Inherit any props passed to it; e.g., multiline, numberOfLines below  
                editable = {true}
                maxLength = {40}
            />
        );  
    }  
}  
export default class UselessTextInputMultiline extends Component {  
    constructor(props) {  
        super(props);  
        this.state = {  
            text: 'Useless Multiline Placeholder',  
        };  
    }  
 
     
    render() {  
        return (  
            <View style={{  
                backgroundColor: this.state.text,  
                borderBottomColor: '#000000',  
                borderBottomWidth: 1,  
               }}
            >
                <UselessTextInput
                    multiline = {true}
                    numberOfLines = {10}
                    onChangeText={(text) => this.setState({text})}
                    value={this.state.text}
                    style={{fontSize: 20}}
                />
            </View>
        );  
    }  
}

Output:

Phần 12: React Native ActivityIndicator

ActivityIndicator sử dụng để hiển thị biểu tượng đang tải hình tròn.

Props

PropsMô tả
animatingLựa chọn để hiển thị biểu tượng (mặc định là true) hoặc ẩn nó đi (false).
sizeĐặt kích cỡ của biểu tượng (‘small’,’large’, số). kích cỡ mặc định là small. Định dạng số chỉ hỗ trợ trên Android.
colorĐặt màu phần nổi của con quay (mặc định là màu xám).
hidesWhenStoppedLựa chọn hiển thị hoặc ẩn biểu tượng khi không có hoạt động (mặc định là true).

Ví dụ về React Native ActivityIndicator

Trong ví dụ này, animating property sẽ đặt hoạt động của biểu tượng thành true, và hiển thị trên màn hình. Khi thành phần được tải lên, biểu tượng chỉ thị hoạt động sẽ được tắt đi sau 6 giây, sử dụng phương thức closeActivityIndicator().

import React, { Component } from 'react'
import {  
    ActivityIndicator,  
    AppRegistry,  
    StyleSheet,  
    Text,  
    View,  
} from 'react-native'
 
export default class ActivityIndicatorDemo extends Component {  
    state = { animating: true }  
    closeActivityIndicator = () => setTimeout(() => this.setState({  
        animating: false }), 6000)  
    componentDidMount = () => this.closeActivityIndicator()  
    render() {  
        const animating = this.state.animating
        return (  
            <View style={[styles.container, styles.horizontal]} >
                <ActivityIndicator  animating = {animating} size="large" color="#ff0000" />
                <ActivityIndicator size="small" color="#44ff00" />
                <ActivityIndicator size="large" color="#rtwrw" />
            </View>
        )  
    }  
}  
 
const styles = StyleSheet.create({  
    container: {  
        flex: 1,  
        justifyContent: 'center'
    },  
    horizontal: {  
        flexDirection: 'row',  
        justifyContent: 'space-around',  
        padding: 10
    }  
})  
 
AppRegistry.registerComponent('App', () => ActivityIndicatorDemo)

Output:

Phần 13: React Native Picker

React Native Picker là một hoạt động để chọn một item từ nhiều lựa chọn. Việc này sẽ tương tự như lựa chọn Dropdown. Picker được sử dụng khi chúng ta cần cung cấp một lựa chọn thay thế từ nhiều phương án.

Nó được sử dụng bằng cách import thành phần Picker từ thư viện react-native.

Các Prop của Picker

PropMô tả
onValueChange( itemValue, itemPosition)Là một callback prop và được gọi khi item được chọn. Nó cần 2 tham số (itemValue:  item (giá trị) được chọn, itemPosition: vị trí (chỉ mục) của item được chọn).
selectedValueTrả về giá trị được chọn.
styleLà một kiểu picket style.
testIDSử dụng để xác định view trong kiểm thử đầu-cuối.
enabledLà một Boolean prop để vô hiệu hóa picker khi được đặt về false. Nếu nó được đặt về false thì người dùng sẽ không thể lựa chọn được.
modeTrên Android, nó xác định cụ thể cách hiển thị các item lựa chọn khi người dùng click vào picker. Nó có các property là “dialog” và “dropdown”. Dialog là chế độ mặc định và sẽ hiển thị là một hộp thoại thông báo. Dropdown hiển thị picker là một view neo thả.
promptĐược sử dụng trên Android với chế độ hộp thoại như là title của hộp thoại.
itemStyleTạo kiểu cho mỗi item của các nhãn picker.

Ví dụ về React Native Picker

Trong ví dụ này, chúng ta sẽ tạo 3 item label trong thành phần Picker. Khi item được chọn từ Picker, nó gọi hàm callback onValueChange và đặt item được chọn vào picker. Chỉ mục của item được đọc từ itemPosition. Vị trí của item được hiển thị trong một thành phần Text.

App.js

import React, { Component } from 'react'
import {StyleSheet,View, Text,Picker} from 'react-native'
 
export default class SwitchExample extends Component {  
    state = {  
        choosenIndex: 0
    };  
 
    render() {  
        return (  
            <View style={styles.container}>
                <Text style={styles.textStyle}>Picker Example</Text>
                <Picker style={styles.pickerStyle}
                        selectedValue={this.state.language}
                        onValueChange={(itemValue, itemPosition) =>
                            this.setState({language: itemValue, choosenIndex: itemPosition})}
                    >
                    <Picker.Item label="Java" value="java" />
                    <Picker.Item label="JavaScript" value="js" />
                    <Picker.Item label="React Native" value="rn" />
                </Picker>
                <Text style={styles.textStyle}> {"Index ="+this.state.choosenIndex}</Text>
            </View>
        );  
    }  
}  
const styles = StyleSheet.create ({  
     container: {  
         flex: 1,  
         alignItems: 'center',  
         justifyContent: 'center',  
     },  
    textStyle:{  
        margin: 24,  
        fontSize: 25,  
        fontWeight: 'bold',  
        textAlign: 'center',  
    },  
    pickerStyle:{  
        height: 150,  
        width: "80%",  
        color: '#344953',  
        justifyContent: 'center',  
    }  
})

Output:

Phần 14: React Native StatusBar

React Native StatusBar là một thành phần để trang trí thanh trạng thái của ứng dụng. Nó được sử dụng bằng cách Import thành phần StatusBar từ thư viện react-native. Chúng ta có thể sử dụng nhiều StatusBar cùng một lúc.

<View>
   <StatusBar
     backgroundColor = "#b3e6ff"
     barStyle = "dark-content"
   />
</View>
<View>
  <StatusBar
     backgroundColor = "#b3e6ff"
     barStyle = "dark-content"
  />
  <View>
    <StatusBar
       hidden={route.statusBarHidden} />
  </View>
</View>

Các Prop của React Native StatusBar

PropsDescription
animatedThanh trạng thái sẽ có hoạt ảnh nếu property của nó thay đổi. Nó hỗ trợ backgrondColor, hidden, và barStyle.
barStyleNó đặt màu của văn bản trên thanh trạng thái.
hiddenDùng để ẩn và hiện thânh trạng thái. Mặc định sẽ là false. Nếu hidden = {false} thì nó sẽ được hiển thị, nếu hidden = {true}, thì nó sẽ ẩn thanh trạng thái.
backgroundColorĐặt màu nền của thanh trạng thái.
translucentNếu được đặt về true, ứng dụng sẽ được xây dựng bên dưới thanh trạng thái.
showHideTransitionHiển thị hiệu ứng chuyển đổi khi hiển thị và ẩn thanh trạng thái. Giá trị mặc định là ‘fade’.
networkActivityIndicatorVisibleKiểm tra biểu tượng mạng có hiển thị hay không. Hỗ trợ trong iOS.

Các phương thức của React Native StatusBar

setHiddensetBarStylesetBackgroundColor
setNetworkActivityIndicatorVisiblesetTranslucent 

React Native StatusBar Ví dụ 1

Hãy tạo một StatusBar đơn giản và thay đổi màu nền của nó.

App.js

import React, { Component } from 'react'
import {  
    View,StyleSheet,AppRegistry,StatusBar
} from 'react-native'
 
export default class ActivityIndicatorDemo extends Component {  
    render() {  
        return (  
            <View style = {styles.container}>
                <StatusBar
                    backgroundColor = "#b3e6ff"
                    barStyle = "dark-content"
                    hidden = {false}    
                    translucent = {true}
                />
            </View>
        )  
    }  
}  
const styles = StyleSheet.create({  
    container: {  
        flex: 1,  
    }  
})  
AppRegistry.registerComponent('App', () => ActivityIndicatorDemo)

Output:

React Native StatusBar Ví dụ 2 (ẩn thanh trạng thái, toàn màn hình)

Trong ví dụ này, chúng ta sẽ ẩn StatusBar bằng property hidden = true. Ẩn StatusBar thì sẽ hiển thị toàn màn hình.

import React, { Component } from 'react'
import {  
    View,StyleSheet,AppRegistry,StatusBar
} from 'react-native'
 
export default class ActivityIndicatorDemo extends Component {  
    render() {  
        return (  
            <View>
                <StatusBar backgroundColor="#b3e6ff" barStyle="light-content" />
                <View>
                    <StatusBar hidden={true} />
                </View>
            </View>
        )  
    }  
}  
const styles = StyleSheet.create({  
    container: {  
        flex: 1,  
    }  
})  
 
AppRegistry.registerComponent('App', () => ActivityIndicatorDemo)

Output:

Phần 15: React Native Switch

React Native Switch là một thành phần điều khiển kiểu Boolean đặt các giá trị của nó thành true hoặc false. Nó có một phương thức callback onValueChange để cập nhật prop giá trị của nó. Nếu prop giá trị không thay đổi, thành phần Switch tiếp tục cung cấp cho prop giá trị thay vì kết quả được kì vọng của bất kì hành động nào của người dùng.

Các props của Switch

PropsMô tả
disabledLà một Boolean property, nếu được đặt về true thì sẽ không thể bật/tắt công tắc. Giá trị mặc định là false.
trackColorSử dụng để tùy chỉnh màu của rãnh công tắc.
ios_backgroundColorĐặt màu nền trên iOS. Nền có thể được hiển thị khi giá trị của công tắc là bị vô hiệu hóa hay khi switch là false.
onValueChangeKích hoạt khi giá trị của công tắc thay đổi.
testIDSử dụng để định vị view trong kiểm thử đầu-cuối.
thumbColorĐổi màu phần nổi của tay nắm công tắc. Khi được chuyển sang iOS, tay nắm công tắc sẽ mất đi phần đổ bóng.
tintColorĐặt màu viền trên iOS và màu nền trên Android khi công tắc được tắt. Property này hiện không còn được dùng nữa; chúng ta sử dụng trackColor để thay thế.
valueLà giá trị của công tắc. Nếu đặt là true thì công tắc bật. Giá trị mặc định là false.

Ví dụ về React Native Switch

Trong ví dụ này, ban đầu chúng ta sẽ đặt giá trị của Switch là false và hiển thị dòng văn bản là 'off'. Khi giá trị của Switch chuyển sang true bằng cách gọi onValueChange thì thành phần Text được chuyển thành 'on'.

App.js

import React, { Component } from 'react'
import {StyleSheet, Switch, View, Text} from 'react-native'
 
export default class SwitchExample extends Component {  
    state = {  
        switchValue: false
    };  
 
    render() {  
        return (  
            <View style={styles.container}>
                <Text style={styles.textStyle}>Switch Example</Text>
                <Text style={styles.textStyle}>{this.state.switchValue ? 'on' :'off'}</Text>
                <Switch
                    value={this.state.switchValue}
                    onValueChange ={(switchValue)=>this.setState({switchValue})}/>
            </View>
        );  
    }  
}  
const styles = StyleSheet.create ({  
     container: {  
         flex: 1,  
         alignItems: 'center',  
         justifyContent: 'center',  
     },  
    textStyle:{  
        margin: 24,  
        fontSize: 25,  
        fontWeight: 'bold',  
        textAlign: 'center',  
        color: '#344953'
    }  
})

Output:

Phần 16: React Native WebView

React Native WebView được sử dụng để tải nội dung web content hoặc trang web. Thành phần WebView được import từ thư viện core react-native. Hiện tại, WebView được thay từ thư viện built-in core react-native, và được đặt trong thư viện react-native-webview.

Chú ý: React Native WebView được khuyển khích import từ thư viện react-native-webview hoặc từ thư viện react-native-community.

Các props của WebView

sourceinjectJavaScriptinjectedJavaScriptonError
onLoadonLoadEndonLoadStartonMessage
originWhitelistrenderErrorstyleuserAgent
htmlurlgeolocationEnabledscrollEnabled
contentInsetbouncesallowFileAccessnativeConfig

Các kiểu nội dung của WebView

Hiển thị code HTML dưới dạng một chuỗi: Chuỗi code HTML được truyền vào html prop trong source property.

<WebView
    source={{html: '<h1>Hello javaTpoint</h1>'}}
/>

Hiển thị trang web nội bộ: Tạo một trang web bên trong một thư mục và chuyển đường dẫn đầy đủ của nó vào source property.

<WebView
    source={require("./resources/index.html")}
/>

Hiển thị trang web từ xa: Tải một trang web từ xa bằng thẻ uri với source property.

<WebView
    source = {{ uri:'https://www.javatpoint.com' }}
/>

React Native WebView Ví dụ 1

Trong ví dụ này, chúng ta sẽ tải một trang web bằng cách truyền URL của nó vào source prop của thành phần WebView.

App.js

import React, { Component } from 'react'
import {  
      View,WebView,StyleSheet,AppRegistry
} from 'react-native'
    
export default class ActivityIndicatorDemo extends Component {  
	render() {  
		return (  
         <View style = {styles.container}>  
             <WebView
                 source = {{ uri:'https://www.javatpoint.com' }}  
             />  
         </View>  
         )  
	}  
}  
const styles = StyleSheet.create({  
     container: {  
         flex: 1,  
     }  
})  
AppRegistry.registerComponent('App', () => ActivityIndicatorDemo)

Output:

React Native WebView Ví dụ 2

Trong ví dụ này, chúng ta sẽ import WebView từ react-native-webview.

App.js

import React, { Component } from 'react'
import {  
    View,StyleSheet,AppRegistry
} from 'react-native'
import {WebView} from 'react-native-webview'
 
export default class ActivityIndicatorDemo extends Component {  
    render() {  
        return (  
            <View style = {styles.container}>
                {/*<WebView
                    source={{html: '<h1>Hello javaTpoint</h1>'}}
                />*/}
             {/*   <WebView
                    source={require("./resources/index.html")}
                />*/}
                <WebView
                    source = {{ uri:'https://www.javatpoint.com' }}
                />
            </View>
        )  
    }  
}  
const styles = StyleSheet.create({  
    container: {  
        flex: 1,  
    }  
})  
 
AppRegistry.registerComponent('App', () => ActivityIndicatorDemo)

Output:

Chú ý: Nếu bạn nhận được thông báo lỗi module react-native-webview không tồn tại trong module map react native. Thì hãy chắc chắn là bạn đã cài đặt các thư viện dưới đây:

  • npm install -g yarn
  • yarn add react-native-webview
  • react-native link react-native-webview

Phần 17: React Native ProgressBar

1. React Native ProgressBarAndroid

Thành phần ProgressBarAndroid của React Native được sử dụng để biểu thị tiến trình của một số hoạt động hay ứng dụng đang tải một cái gì đó. Thành phần ProgressBarAndroid chỉ hoạt động trên nền tảng Android. Để sử dụng thanh tiến trình trên nền tảng iOS thì chúng ta sẽ sử dụng thành phần ProgressViewIOS .

Các Props của ProgressBarAndroid

PropsKiểuBắt buộcMô tả
animatingboolKhôngĐược sử dụng để hiện hoặc ẩn thanh tiến trình. Giá trị mặc định là true để hiện, (false để ẩn).
colorcolorKhôngĐặt màu của thanh tiến trình.
indeterminateindeterminateTypeKhôngHiển thị trạng thái tiến trình trung bình của thanh tiến trình. Chỉ có thể là false nếu styleAttr của thanh tiến trình là Horizontal.
progressnumberKhôngLà giá trị của tiến trình giữa 0 và 1.
styleAttrenumKhôngĐặt kiểu của thanh tiến trình. Có nhiều kiểu thanh tiến trình trong React Native như Horizontal, Normal (mặc định), Small, Large, Inverse, SmallInverse, và LargeInverse.
testIDstringKhôngSử dụng để định vị view trong kiểm thử đầu cuối.

Ví dụ về React Native ProgressBarAndroid

Trong ví dụ này, chúng ta sẽ đặt ProgressBarAndroid ngang và thực hiện hành động trên thành phần TouchableOpacity. Trạng thái tiến trình sẽ được hiển thị trong thành phần Text chỉ lên đến 3 chữ số.

import React, { Component } from 'react';  
import { Platform, StyleSheet, View, Text, TouchableOpacity, ProgressBarAndroid, ProgressViewIOS } from 'react-native';  
export default class MyApp extends Component<{}>{  
  constructor()  {  
    super();  
    this.state = {  
      progressStatus: 0,  
    }  
  }  
 
  start_Progress = () => {  
    this.value = setInterval( () => {  
      if(this.state.progressStatus <= 1){  
        this.setState({progressStatus: this.state.progressStatus+ .01})  
      }  
    }, 100 );  
  }  
 
  stop_Progress = () =>{  
   clearInterval(this.value);  
  }  
 
  clear_Progress =()=>{  
    this.setState({progressStatus : 0.0})  
  }  
 
  render()  
  {  
    return(  
      <View style = { styles.MainContainer }>
        <Text style = {{fontSize: 20, color: '#000'}}> Progress Value: { parseFloat((this.state.progressStatus * 100).toFixed(3))} %</Text>{
            ( Platform.OS === 'android' )  
            ?  
              ( <ProgressBarAndroid styleAttr = "Horizontal" progress = { this.state.progressStatus } indeterminate = { false } /> )  
            :  
              ( <ProgressViewIOS progress = { this.state.progressStatus } /> )  
        }
        <TouchableOpacity activeOpacity = { 1 } style = { styles.button } onPress = { this.start_Progress }>
          <Text style = { styles.TextStyle }> Start Progress </Text>
        </TouchableOpacity>
        <TouchableOpacity activeOpacity = { 1 } style = { styles.button } onPress = { this.stop_Progress }>
          <Text style = { styles.TextStyle }> Stop Progress </Text>
        </TouchableOpacity>
        <TouchableOpacity activeOpacity = { 1 } style = { styles.button } onPress = { this.clear_Progress }>
          <Text style = { styles.TextStyle }> Reset Progress </Text>
        </TouchableOpacity>
      </View>
    );  
  }  
}  
 
const styles = StyleSheet.create(  
{  
  MainContainer:
  {  
    flex: 1,  
    justifyContent: 'center',  
    paddingTop: ( Platform.OS === 'ios' ) ? 20 : 0,  
    margin: 20
  },  
 
  button: {  
  width: '100%',  
  backgroundColor: '#00BCD4',  
  borderRadius:5,  
  padding: 10,  
  marginTop: 10,  
 
},  
 
TextStyle:{  
    color:'#fff',  
    textAlign:'center',  
    fontWeight: 'bold',  
}  
});

Output:

2. React Native ProgressBar Với Animated

Trong phần trước về ProgressBarAndroid chúng ta đã học cách hiển thị thanh tiến trình mặc định. Tuy nhiên, chúng ta cũng có thể tùy chỉnh thanh tiến trình với lớp Animated.

Ví dụ về React Native ProgressBar với Animated

Để tạo một thanh tiến trình có hoạt ảnh thì chúng ta sẽ import lớp Animated. Thêm các thành phần Animated.View và Animated.Text vào trong View. Đặt giá trị ban đầu cho biến trạng thái tiến trình thành 0 và gọi phương thức onAnimate(). Phương thức này sẽ kích hoạt khi màn hình tải xong hoàn toàn (gọi componentDidMount()). Thêm một listener trên phương thức onAnimate() method để cập nhật trạng thái tiến trình.

App.js

import React, {Component} from 'react';  
import {Platform, StyleSheet, Text, View, Animated} from 'react-native';  
 
export default class App extends Component {  
    state={  
        progressStatus: 0,  
    }  
    anim = new Animated.Value(0);  
    componentDidMount(){  
        this.onAnimate();  
    }  
    onAnimate = () =>{  
        this.anim.addListener(({value})=> {  
            this.setState({progressStatus: parseInt(value,10)});  
        });  
        Animated.timing(this.anim,{  
             toValue: 100,  
             duration: 50000,  
        }).start();  
    }  
  render() {  
    return (  
      <View style={styles.container}>
            <Animated.View
                style={[  
                    styles.inner,{width: this.state.progressStatus +"%"},  
                ]}
            />
            <Animated.Text style={styles.label}>
                    {this.state.progressStatus }%  
            </Animated.Text>
      </View>
    );  
  }  
}  
const styles = StyleSheet.create({  
    container: {  
    width: "100%",  
    height: 40,  
    padding: 3,  
    borderColor: "#FAA",  
    borderWidth: 3,  
    borderRadius: 30,  
    marginTop: 200,  
    justifyContent: "center",  
  },  
  inner:{  
    width: "100%",  
    height: 30,  
    borderRadius: 15,  
    backgroundColor:"green",  
  },  
  label:{  
    fontSize:23,  
    color: "black",  
    position: "absolute",  
    zIndex: 1,  
    alignSelf: "center",  
  }  
});

Trạng thái tiến trình của thanh tiến trình được cập nhật với chu kỳ mỗi 0.5 giây (50000 micro giây). Cùng lúc đó thì chiều dài của thanh tiến trình được quyết định bằng trạng thái của tiến trình, và trạng thái của nó được đặt vào thành phần Animated.Text.

Output:

– Sưu tầm –

(Visited 85 times, 1 visits today)

TÍN NGHĨA – Đơn vị chuyên cung cấp dịch vụ công nghệ thông tin với chi phí hợp lý nhất, phục vụ cho mọi đối tượng, …

Liên hệ với TINNGHIA ngay hôm nay để có báo giá tốt nhất:
Email: tinnghiaco39@gmail.com – Hotline: 0915.631.868 – 0986.020.123
Webiste: www.tinnghiaco.com
Facebook: facebook.com/dntinnghia
Trong trường hợp tổng đài BẬN LIÊN TỤC hoặc QUÁ TẢI đơn hàng, Quý khách vui lòng để lại thông tin của mình thông qua biểu mẫu liên hệ hoặc tin nhắn để TINNGHIA liên hệ lại và giải đáp mọi thắc mắc của Quý khách trong thời gian sớm nhất.
Xin chân thành cảm ơn Quý khách đã quan tâm tới dịch vụ của TINNGHIA./.