hysryt / wiki

https://hysryt.github.io/wiki/
0 stars 0 forks source link

style-components #197

Open hysryt opened 2 years ago

hysryt commented 2 years ago

https://styled-components.com/

React用のライブラリ CSS in JS

hysryt commented 2 years ago

インストール

npx create-react-app my-app
cd my-app
npm install --save style-components

import styled from 'styled-components';

const Button = styled.button`
  background: red;
`;

function App() {
  return (
    <div className="App">
      <Button>button</Button>
    </div>
  );
}

export default App;

styled.button でReactコンポーネントを生成している。

この構文はタグ付きテンプレート文字列リテラルというJavaScriptに元々備わっている構文。

プロパティによってスタイルを変える

import styled, { css } from 'styled-components';

const Button = styled.button`
  background: red;
  ${props => props.primary && css`
    background: blue;
  `}
`;

function App() {
  return (
    <div className="App">
      <Button>button</Button>
      <Button primary>button</Button>
    </div>
  );
}

export default App;