NativeBase v3의 올바른 사용
46809 단어 reactjavascriptreactnativetypescript
우리는 많은 사람들이 v3의 잠재력을 충분히 이용하지 못했다는 것을 깨달았고, 때로는 많은 사람들이 그것이 매우 복잡할 것이라고 생각했다.따라서 NativeBase 플랫폼의 단순성을 보여주고자 합니다.
따라서 NativeBase와 함께 v3의 아이디어를 활용하여 아름답고 효율적인 UI를 만드는 방법에 대해 설명합니다.
이 문서에서는 다음 여섯 가지 섹션을 살펴보겠습니다.
새 프로젝트를 만들고 NativeBase를 사용하려는 경우 어셈블리 라이브러리에서 제공하는 예제 템플릿을 사용하는 것이 좋습니다.이는 시간을 절약하고 명암 모드를 어떻게 실현하는지 이해하는 좋은 출발점이 될 것이다.사용자 정의 테마 설정의 일별을 제공합니다. 사용자의 요구에 따라 편집하거나 삭제할 수 있습니다.
expo, CRA, React Native 및 Next에서 템플릿을 설정하는 데 사용되는 명령입니다.다음은 js 항목을 참고하시기 바랍니다.
엑스포 프로젝트에서 템플릿을 구현하려면 다음 코드를 사용합니다.
JavaScript
expo init my-app --template expo-template-native-base
TypeScript
expo init my-app --template expo-template-native-base-typescript
create react app 프로젝트에서 템플릿을 구현하려면 다음 코드를 사용합니다.
JavaScript
npx create-react-app my-app --template nativebase
TypeScript
npx create-react-app my-app --template nativebase-typescript
React 기본 프로젝트에서 템플릿을 구현하려면 다음 코드를 사용합니다.
JavaScript
npx react-native init my-app --template react-native-template-native-base
TypeScript
npx react-native init my-app --template react-native-template-native-base-typescript
NextJS 프로젝트에서 템플릿을 구현하려면 다음 코드를 사용합니다.
JavaScript
yarn create next-app -e https://github.com/GeekyAnts/nativebase-templates/tree/master/nextjs-with-native-base
TypeScript
yarn create next-app -e https://github.com/GeekyAnts/nativebase-templates/tree/master/nextjs-with-native-base-typescript
All the templates on NativeBase v3 come with a customTheme setup using which you can customise themes very easily.
2. 유틸리티 및 스타일시트 APINativeBase의 모든 사용자는 가능한 한 유틸리티
StyleSheets
를 사용할 것을 강력히 권장합니다.NativeBase components에서는 다양한 유틸리티를 사용할 수 있습니다.너는 그들의 명단here을 찾을 수 있다.
두 가지 방법을 비교한 예를 살펴보겠습니다.
예.
React Native
StyleSheet
를 사용하도록 선택한 경우 아래 코드를 참조하십시오.import * as React from "react";
import { Text, View, StyleSheet } from "react-native";
export default function App() {
return (
// The code looks cleaner here but it's really hard to tell what is what and how that component would look.
<View style={styles.container}>
<View style={styles.card}>
<View style={styles.row}>
<Text style={styles.subHeading}>Business</Text>
<Text style={styles.period}>1 month ago</Text>
</View>
<Text style={styles.heading}>Marketing License</Text>
<Text style={styles.paragraph}>
Unlock powerfull time-saving tools for creating email delivery and
collecting marketing data
</Text>
<Text style={styles.link}>Read More</Text>
</View>
</View>
);
}
// You need to switch back and forth to understand which component has which style
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center",
backgroundColor: "#374151",
},
card: {
width: 296,
backgroundColor: "#f9fafb",
padding: 20,
borderRadius: 8,
},
paragraph: {
marginTop: 8,
fontSize: 14,
fontWeight: "medium",
color: "#6b7280",
},
period: {
fontSize: 10,
color: "#a1a1aa",
},
heading: {
marginTop: 12,
fontSize: 20,
fontWeight: 500,
},
link: {
marginTop: 8,
color: "#0891b2",
fontWeight: "medium",
fontSize: 12,
},
subHeading: {
fontSize: 12,
color: "#71717a",
},
row: {
flexDirection: "row",
justifyContent: "space-between",
alignItems: "flex-start",
},
});
엑스포 간식:https://snack.expo.dev/pu9jBPcutimport React from 'react';
import {
Center,
NativeBaseProvider,
HStack,
Box,
Text,
Spacer,
} from 'native-base';
export default () => {
return (
// Though it doesn't look as slick as the previous example but try reading the code.
<NativeBaseProvider>
<Center flex={1} bg="coolGray.700">
{// Every line of code is so much intuitive, one can easily understand what it does.}
<Box bg="blueGray.50" p="5" w="296" rounded="8">
<HStack alignItems="flex-start">
<Text fontSize="12" color="gray.500" fontWeight="medium">
Business
</Text>
<Spacer />
<Text fontSize="10" color="gray.400">
1 month ago
</Text>
</HStack>
<Text mt="3" fontWeight="medium" fontSize="20">
Marketing License
</Text>
<Text mt="2" fontSize="14" color="gray.500">
Unlock powerfull time-saving tools for creating email delivery and
collecting marketing data
</Text>
<Text mt="2" fontSize="12" fontWeight="medium" color="cyan.600">
Read More
</Text>
</Box>
</Center>
</NativeBaseProvider>
);
};
엑스포 간식:https://snack.expo.dev/AGNgFxZ4L실용 도구를 사용하는 장점은 다음과 같다.
Alternatively, you can use Utility Props in StyleSheet APIs by creating objects of utility props and spreading them even through this method is not recommended.
3. 단일 소스에서 가져오기코어 React 라이브러리에서 응용 프로그램을 개발할 때 일반적으로 필요한 몇 개의 일반 구성 요소를 선택하고
Factory
함수를 통해 전달합니다.이렇게 하면 단일 소스에서 가져오고 NativeBase에서 제공하는 모든 우수한 제품을 패키지화할 수 있으므로 다른 생산 라인에서 새 구성 요소를 가져올 염려가 없습니다.NativeBase v3을 사용하는 경우 NativeBase 라이브러리에서 다음 구성 요소를 사용하는 것이 좋습니다.
import {
ScrollView,
View,
KeyboardAvoidingView,
StatusBar,
FlatList,
SectionList,
} from "native-base";
이러한 구성 요소와 문서 링크는 다음과 같습니다.NativeBase에서는 기술 커뮤니티의 개발 경험을 단순화하는 데 많은 노력을 기울였습니다.이 사상을 확장하기 위해서, 우리는 일부 위조 도구를 제공했는데, 그것들은 당신이 응용 프로그램을 만드는 방식을 완전히 바꾸었다.우리는 몇 가지 예를 통해 이 점을 이해합시다.
색상 모드 위조 아이템:
NativeBase는 현재 테마와 색 모드를 검사하기 위해 갈고리를 제공합니다. 즉
Light
또는 Dark
. 그러나 갈고리 가져오기, 갈고리 호출, 조건부 색 모드 검사 등 번거로운 작업을 가져올 수 있습니다.반대로
_light
와 _dark
위조 아이템에 아이템을 추가하면 NativeBase는 관련 색상 모드만 적용됩니다.예를 들어 이 점을 검증해 봅시다.backgroundColor
중 하나light mode
='primary.500'이 필요하고 dark mode
중 기본적인 배경색이 있어야 한다고 가정했다.dark mode
에서'primary.800'이고 light mode
에서 기본 색이어야 한다.import React from "react";
import {
Button,
Center,
useColorMode, // Step 1 Importing the hook
NativeBaseProvider,
} from "native-base";
export function TestApp() {
const { colorMode } = useColorMode(); // Step 2 Calling the hook
return (
<Button
bg={colorMode === "light" ? "primary.500" : "primary.400"} // Step 3 Conditionally applying props
_text={colorMode === "light" ? { color: "primary.800" } : "white"} // Step 3 Conditionally applying props
>
Button
</Button>
);
}
export default () => {
return (
<NativeBaseProvider>
<Center flex={1}>
<TestApp />
</Center>
</NativeBaseProvider>
);
};
다음 코드를 사용하여 _light
및 _dark
위조 아이템을 사용하여 현재 테마와 색상 모드를 검사합니다.import React from "react";
import { Button, Center, NativeBaseProvider } from "native-base";
export function TestApp() {
return (
<Button
_light={{ bg: "primary.500" }} // Step 1 Conditionally pass props to _light and _dark
_dark={{ _text: { color: "primary.800" } }}
>
Button
</Button>
);
}
export default () => {
return (
<NativeBaseProvider>
<Center flex={1}>
<TestApp />
</Center>
</NativeBaseProvider>
);
};
다음 그림 설명은 이 위조 아이템을 어떻게 사용해서 일을 더욱 간단하게 하는지 보여주는 예입니다.플랫폼 위조 아이템:
이렇게 하는 것은 플랫폼을 기반으로 하는 구성 요소에 도구를 조건부로 전달하기 위해서라는 것을 명심해라.운영 체제?
<Input
numberOfLines={Platform.OS === "android" ? "4" : null}
width={Platform.OS === "web" ? "48" : "80%"}
/>
최신 버전의 NativeBase에서는 더 이상 문제가 되지 않습니다!_web
,_android
와_ios
아이템을 간단하게 사용하고 관련 아이템을 어떤 플랫폼에 전달하면 시작할 수 있습니다.<Input _android={{ numberOfLines: 4 }} _web={{ width: "48" }} width="80%" />
특정 플랫폼이 우선순위보다 높으면 플랫폼 아이템이 다른 아이템을 덮어씁니다.NativeBase에는 더 많은 위조 도구가 있습니다. 다음 블로그에서 소개하고 이를 실현하는 안내서입니다.그곳에서도 널 볼 수 있었으면 좋겠어!
5. 고리 활용
NativeBase는 또한 많은 사용하기 쉬운 사용자 정의 연결을 제공하여 응용 프로그램을 신속하게 구축할 수 있도록 도와줍니다. 따라서 가능한 한 사용하십시오.
예를 들어
useDisclose
갈고리를 어떻게 실현하는지 봅시다.다음 코드를 참조하십시오.import React from "react";
import {
Modal,
Button,
Center,
useDisclose,
NativeBaseProvider,
} from "native-base";
function UseDiscloseExample() {
// handles common open, close, or toggle scenarios
const { isOpen, onOpen, onClose } = useDisclose();
// no need to create your own state and helper functions
return (
<>
<Modal isOpen={isOpen} onClose={onClose}>
<Modal.Content>
<Modal.CloseButton />
<Modal.Header fontSize="4xl" fontWeight="bold">
Hello World
</Modal.Header>
<Modal.Body>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Quos quasi
cupiditate expedita, ipsa corporis officia totam similique delectus!
Debitis esse, ea blanditiis iste enim iure at odit fugiat autem.
Accusamus?
</Modal.Body>
<Modal.Footer>
<Button colorScheme="blue" mr={1}>
Save
</Button>
<Button onPress={onClose}>Close</Button>
</Modal.Footer>
</Modal.Content>
</Modal>
<Button onPress={onOpen}>Open Modal</Button>
</>
);
}
export default function () {
return (
<NativeBaseProvider>
<Center flex={1}>
<UseDiscloseExample />
</Center>
</NativeBaseProvider>
);
}
또 다른 중요한 갈고리는 useBreakpointValue
인데, 현재 단점의 값을 되돌려줍니다.다음 코드를 참조하십시오.import React from "react";
import {
Box,
useBreakpointValue,
NativeBaseProvider,
Center,
} from "native-base";
function UseBreakpointValueExample() {
// the value of color will change based on the screen sizes.
const color = useBreakpointValue({
base: "red.200",
sm: "blue.200",
md: "blue.200",
});
return (
<Box bg={color} w={"100px"}>
This is a box
</Box>
);
}
export default function () {
return (
<NativeBaseProvider>
<Center flex={1}>
<UseBreakpointValueExample />
</Center>
</NativeBaseProvider>
);
}
다음은 기타 갈고리와 문서의 목록입니다.NativeBase v3 에서도 애플리케이션 개발 환경의 엄격한 수준을 제어할 수 있는 엄격한 모드가 있습니다.엄격 모드는 전체 코드 라이브러리에서 최선의 실천을 유지할 수 있는 매우 편리한 도구로 NativeBase 설정 설정에 전달할 수 있는 설정입니다.
그것은
error
, warn
와 off
세 개의 값을 포함한다.기본값은 off
입니다.선택한 옵션에 따라 항목의 모든 아이템을 검사하고 아이템token values
값만 전달하여 theme
의 정확한 사용 여부를 검사합니다string
.이 조건이 충족되지 않으면 오류/경고가 발생하거나 작업이 수행되지 않습니다.만약 이전에 실용 프로그램 도구에 숫자를 전달하는 데 익숙해졌다면, 문자열 표시를 사용하십시오. 3.2.0 버전에 새로운 표시 값이 추가되어 진퇴양난의 국면을 초래할 수 있습니다.다음 코드를 참조하십시오.
// If you previously had something like this in your code
<Box p={4} mx={3} my="12px" bg="primary.400" width="50%" >
Hello World
</Box>
// Then now the correct way would be
<Box p="4" mx="3" my="3" bg="primary.400" width="1/2" >
Hello World
</Box>
결론NativeBase의 최신 기능을 가장 좋은 방법으로 활용하는 방법에 대한 소개가 끝났습니다.NativeBase는 최근 향상된 기능을 통해 액세스 및 사용자 정의 가능한 구성 요소를 생성할 수 있습니다.나는 본고가 당신에게 v3에 추가된 새로운 기능을 시도해 보라고 제시할 수 있기를 바랍니다.
앞으로 NativeBase에서 제공하는 풍부한 구성 요소 라이브러리로 예쁜 프로그램을 만들 수 있도록 더 많은 안내서를 제공할 것입니다.
here를 클릭하여 저희 Discord 채널에서의 실험을 알려주세요.
이 문장은 최초로 로시트 싱거가 발표한 것이다
Reference
이 문제에 관하여(NativeBase v3의 올바른 사용), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/nativebase/using-nativebase-v3-the-right-way-4a1f텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)