طراحی Material Button در react native


سلام دوستان . در این آموزش متنی قصد داریم یاد بگیریم که چجوری یک Material Button در react native طراحی کنیم.Button یکی از کامپوننت های پرکاربرد react native است زیرا بدون Button کاربر نمیتواند عملیات خاصی انجام بدهد.به طور پیش فرض react native از یک استایل Material برای Button استفاده میکند.بنابراین در این آموزش متنی ما یک button ایجاد میکنیم و با استفاده از Props مشخص میکنیم که هروقت کاربر بر روی این دکمه کلیک کرد یک پیام به صورت dialog نمایش داده شود.
1.ساخت یک پروژه جدید.اگه نمیدونید چطور اینکارو بکنید،پیشنهاد میکنم دوره آموزش مقدماتی react native رو ببینید(برای مک هم میتونید مقالهآموزش نصب react native بر روی مک رو مطالعه کنید)
2.اضافه کردن کامپوننت های AppRegistry,Button, Alert و View در بلاک import
1 |
import { AppRegistry, View, Button, Alert } from 'react-native'; |
3. ایجاد تابع ()SampleFunction درون کلاس اصلی.در این تابع ما یک پیغام به صورت dialog به کاربر نمایش میدهیم.
1 2 3 4 5 |
SampleFunction() { Alert.alert('Button Clicked!') } |
4.اضافه کردن تگ View در بلاک render return
1 2 3 4 5 6 7 8 9 |
render() { return ( <View> </View> ); } |
5.استایل دهی به View
1 2 3 4 5 6 7 8 9 |
render() { return ( <View style={{flex :1, justifyContent: 'center', margin: 10 }}> </View> ); } |
6.اضافه کردن Button درون View
1 2 3 4 5 6 7 8 9 |
render() { return ( <View style={{flex :1, justifyContent: 'center', margin: 10 }}> <Button /> </View> ); } |
7.مشخص کردن رنگ و عنوان Button
1 2 3 4 5 6 7 8 9 |
render() { return ( <View style={{flex :1, justifyContent: 'center', margin: 10 }}> <Button title="Sample Button" color="#2196F3" /> </View> ); } |
8.اضافه کردن onPress به Button
1 2 3 4 5 6 7 8 9 |
render() { return ( <View style={{flex :1, justifyContent: 'center', margin: 10 }}> <Button onPress={ } title="Sample Button" color="#2196F3" /> </View> ); } |
9.فراخوانی تابع()SampleFunction در onPress
1 2 3 4 5 6 7 8 9 |
render() { return ( <View style={{flex :1, justifyContent: 'center', margin: 10 }}> <Button onPress={ this.SampleFunction } title="Sample Button" color="#2196F3" /> </View> ); } |
10.کد کامل برنامه در فایل index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import React, { Component } from 'react'; import { AppRegistry, View, Button, Alert } from 'react-native'; class Myproject extends Component { SampleFunction() { Alert.alert('Button Clicked!') } render() { return ( <View style={{flex :1, justifyContent: 'center', margin: 10 }}> <Button onPress={ this.SampleFunction } title="Sample Button" color="#2196F3" /> </View> ); } } AppRegistry.registerComponent('Myproject', () => Myproject); |
اسکرین شات:
دیدگاهتان را بنویسید