React Nativeの独自Componentにstyled-componentsを適用する


Published on May 16, 2020

React Nativeの独自Componentにstyled-componentsを適用する方法を解説します。

標準のViewやTextといったComponentにstyled-componentsを適用するのは簡単ですが、自作Componentに適用しようとしてハマったので・・・。

記事作成時のstyled-componentsのVer.は5.1.0です。


styled-componentsをインストール


terminal
$ yarn add styled-components

$ yarn add -D @types/styled-components


独自Componentの作成(失敗例)


CustomComponent.tsx
import React from 'react';
import styled from 'styled-components/native';
import {Text} from 'react-native';

export const CustomComponent = () => {
  return (
    <StyledView style={props.style}>
      <Text>Hello</Text>
    </StyledView>
  );
};

const StyledView = styled.View`
  align-items: center;
  justify-content: center;
  height: 100%;
`;


独自Componentの作成(成功例)


propsにstyleを渡してあげるとうまくいきます。

CustomComponent.tsx
import React from 'react';
import styled from 'styled-components/native';
import {Text, ViewStyle, StyleProp} from 'react-native';
type PropsType = {                                        style?: StyleProp<ViewStyle>;                        };                                                      export const CustomComponent = (props: PropsType) => {  return (
    <StyledView style={props.style}>      <Text>Hello</Text>
    </StyledView>
  );
};

const StyledView = styled.View`
  align-items: center;
  justify-content: center;
  height: 100%;
`;


CustomComponentの呼び出し


App.tsx
import React from 'react';
import {SafeAreaView} from 'react-native';
import {CustomComponent} from './CustomComponent';
import styled from 'styled-components/native';

const App = () => {
  return (
    <SafeAreaView>
      <StyledCustomComponent />
    </SafeAreaView>
  );
};

const StyledCustomComponent = styled(CustomComponent)`
  background: lightpink;
`;

export default App;

styled-components

If you like it, share it!