はじめに
React Nativeでのstyled-componentsの使い方についての記事があまり無かったので備忘録として書いておきます。何か気づき次第追加するかもしれません。
前提
TypeScriptの使用
yarnの使用
styled-componentsが書ける
インストール
styled-componentsをReact Nativeで使用するためには専用のパッケージも追加する必要があります。
yarn add styled-components
yarn add -D @types/styled-components @types/styled-components-react-native
最小構成で動作確認
expo initで作成されるテンプレートを使ってstyled-componetsでHello,Worldしてみました。
App.tsx
import { StatusBar } from "expo-status-bar";
import { Text } from "react-native";
import React from "react";
import styled from "styled-components/native";
export default function App() {
return (
<SComponentView>
<StatusBar style="auto" />
<Text>Hello,World</Text>
</SComponentView>
);
}
const SComponentView = styled.View`
flex: 1;
background-color: #fff;
align-items: center;
justify-content: center;
`;
注意点はstyledはreactnative専用のものをimportしないといけない点くらいです。ほかはだいたい一緒かなと思います。
おわりに
簡単ですね。ReactとReact Nativeで開発するならstyled-componentsがいいかなと思います。
参考文献
[1]:React Native で styled-components を使う