Home Tutorial React Native React Native – Bài 18: Picker

React Native – Bài 18: Picker

2 min read
0
129

Picker là bộ chọn đơn giản (tương tự select trong web) với các tùy chọn được show lên và bạn chọn 1 trong các option đó.

Bước 1: Tạo tệp

Tại đây, thư mục App.js sẽ được sử dụng làm thành phần trình bày.

App.js

import React from 'react'
import PickerExample from './PickerExample.js'

const App = () => {
   return (
      <PickerExample />
   )
}
export default App

Bước 2: Logic

this.state.user được sử dụng để kiểm soát bộ chọn.

Chức năng updateUser sẽ được kích hoạt khi người dùng được chọn.

Bộ chọnExample.js

import React, { Component } from 'react';
import { View, Text, Picker, StyleSheet } from 'react-native'

class PickerExample extends Component {
   state = {user: ''}
   updateUser = (user) => {
      this.setState({ user: user })
   }
   render() {
      return (
         <View>
            <Picker selectedValue = {this.state.user} onValueChange = {this.updateUser}>
               <Picker.Item label = "Steve" value = "steve" />
               <Picker.Item label = "Ellen" value = "ellen" />
               <Picker.Item label = "Maria" value = "maria" />
            </Picker>
            <Text style = {styles.text}>{this.state.user}</Text>
         </View>
      )
   }
}
export default PickerExample

const styles = StyleSheet.create({
   text: {
      fontSize: 30,
      alignSelf: 'center',
      color: 'red'
   }
})

đầu ra

React Native Picker

Nếu bạn nhấp vào tên, nó sẽ nhắc bạn cả ba tùy chọn như –

React Native Picker

Và bạn có thể chọn một trong số chúng và kết quả sẽ như thế nào.

React Native Picker

Load More Related Articles
Load More By quangvu
Load More In React Native

Check Also

Tự làm web chatGPT đơn giản cho phép dùng nhiều OpenAI key

Trong thời đại công nghệ phát triển như hiện nay, chatbot đang dần trở thành một giải pháp…