2017-06-26 4 views
1

${props => props.myProp}は、どうすればstyled-componentsに書き込むことができますか?例えば

、我々はボタンスタイリングされている場合:私たちは${props => props.myProp}のようなものを書く必要があるドキュメントherehere

const Button = styled.button` 
    background: ${props => props.background}; 
    color: ${props => props.color}; 
`; 

render(
    <div> 
     <Button 
      background="red" 
      color="white" 
     > 
      Example 1 
     </Button> 

     <Button 
      background="black" 
      color="yellow" 
     > 
      Example 2 
     </Button> 
    </div> 
); 

を。しかし、これは迷惑と不必要に見えます。 ${props.myProp}と書くことができれば良いでしょう。

私の現在の回避策は何か書くことです:

const Button = styled.button`${props => ` 
    background: ${props.background}; 
    color: ${props.color}; 
`}`; 

をが、これは明確なだけ${props.color}を使用してのように簡単ではありません。

これはどうすればできますか?

答えて

2

あなたはどこでもあなたが小道具の小道具を抽出したい利用できるヘルパー関数を書くことができます:

const props = name => p => p[name]; 

次にようにそれを使用します。props('bgColor')を使用して

const Button = styled.button` 
    background: ${props('bgColor')}; 
`; 

は同じくらい近いです正しい動作を維持しながら、との構文の類似性を得ることができます。

あなたは細心になりたい場合は、代わりに直接文字列を渡すの変数を作成することができます。

const bg = 'bgColor'; 
const Button = styled.button` 
    background: ${props(bg)}; 
`; 

コメントでmxstbrによって示唆されるように、あなたもstyled-propsパッケージを好むかもしれません。

+1

あなたは['styled-props'](https://github.com/RafalFilipek/styled-props)パッケージも好きかもしれません! :) – mxstbr

+0

@mxstbrこれは良い提案です:) – nem035

関連する問題