몇 분 만에 React + TypeScript + Tailwind + 클래스 이름 시작하기
17795 단어 reacttailwindcsstypescripttutorial
create-react-app
를 부트스트랩하고 classnames
를 사용하여 일부 상태 기반 스타일 지정을 통해 모든 것을 신속하게 시작하고 실행할 수 있는 방법을 살펴보겠습니다.설치
먼저
create-react-app
로 TypeScript React 앱을 만들어야 합니다.둘째, 오늘 필요한 다른 패키지를 설치합니다.
# Create the app
npx create-react-app hello-tailwind --template typescript
# Change into our new app
cd hello-tailwind
# Using Yarn
yarn add tailwindcss classnames @types/classnames
package.json 업데이트 중
이 부분은 최신 업데이트로 Dave Ceddia's post에서 빠른 영감을 얻었습니다.
다음과 같이 스크립트를 업데이트해 보겠습니다.
{
"scripts": {
"build:tailwind": "tailwindcss build src/index.css -o src/tailwind.output.css",
"prestart": "npm run build:tailwind",
"prebuild": "npm run build:tailwind"
}
}
prestart
및 prebuild
스크립트는 start
및 build
스크립트가 실행되기 전에 실행됩니다. index.css
파일을 빌드하고 src/tailwind.output.css
로 출력하도록 지시하고 있습니다.Tailwind 가져오기 추가
다음과 같이 업데이트
src/index.css
:@tailwind base;
@tailwind components;
@tailwind utilities;
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto",
"Oxygen", "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans",
"Helvetica Neue", sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New",
monospace;
}
그런 다음
index.tsx
에서 index.css
로 가져오기를 변경하기 위해 tailwind.output.css
파일을 업데이트해야 합니다.import React from "react"
import ReactDOM from "react-dom"
import "./tailwind.output.css"
import App from "./App"
import * as serviceWorker from "./serviceWorker"
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById("root")
)
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister()
이제 우리는 달릴 준비가 되었습니다!
App.tsx로 놀기
실행
yarn start
하여 응용 프로그램을 시작하고 실행합니다.실행되면
App.tsx
파일을 다음과 같이 업데이트해 보겠습니다.import React from "react"
function App() {
return (
<div className="bg-gray-200 flex items-center justify-center h-screen">
<button
className="p-3 rounded-sm bg-blue-500 hover:bg-blue-700"
onClick={() => setToggle(!toggle)}
>
Toggle
</button>
</div>
)
}
export default App
앱을 실행하면 이제 다음이 표시됩니다.

기본 응용 프로그램
이러한 클래스 이름은 Tailwind docs 에서 가져옵니다. 문서는 매우 사용자 친화적입니다! CSS 속성을 검색하고 거기에서 적용하십시오.
As an added bonus, if you are a VSCode user, check out their VSCode extension to help autocomplete classnames!
로직을 기반으로 작동하도록 App.tsx 파일 업데이트
이제
useState
를 기반으로 논리를 추가하여 다른 상태 간에 전환할 수 있습니다.다음을 표시하도록 업데이트
App.tsx
:import React from "react"
// import cx from 'classnames';
function App() {
const [toggle, setToggle] = React.useState<boolean>(false)
console.log("toggle", toggle)
const buttonClasses = toggle
? "bg-red-500 hover:bg-red-500"
: "bg-blue-500 hover:bg-blue-500"
return (
<div className="bg-gray-200 flex items-center justify-center h-screen">
<button
className={`p-3 rounded-sm ${buttonClasses}`}
onClick={() => setToggle(!toggle)}
>
Toggle
</button>
</div>
)
}
export default App
이제 앱을 실행하면 버튼을 클릭하면 배경이 빨간색으로 변경되는 것을 볼 수 있습니다!

전환된 앱 상태
클래스 이름 사용
더 복잡한 논리의 경우 classnames package을 사용하여 적용할 클래스 이름을 정의할 수 있습니다.
import React from "react"
import cx from "classnames"
function App() {
const [toggle, setToggle] = React.useState<boolean>(false)
const buttonClasses = cx({
"bg-blue-500 hover:bg-blue-700": !toggle,
"bg-red-500 hover:bg-red-500": toggle,
})
return (
<div className="bg-gray-200 flex items-center justify-center h-screen">
<button
className={`p-3 rounded-sm ${buttonClasses}`}
onClick={() => setToggle(!toggle)}
>
Toggle
</button>
</div>
)
}
export default App
이 예제는 사소하지만 소품을 기반으로 변형을 정의할 때 중요합니다.
toggle
를 status === 'error'
등과 같은 논리로 교체하여 응용 프로그램을 통해 다양한 가능성을 반영할 수 있습니다.결론
이것은 핵심 세부 사항에 들어가지 않고 Tailwind를 시작하고 실행하는 방법에 대한 빠른 모닝 커피 및 블로그 게시물이었습니다.
Tailwind는 훌륭한 평판을 가지고 있으며 그만한 이유가 있습니다. 이 플레이그라운드를 사용하여 제공하는 다른 기능을 시도해 볼 것을 적극 권장합니다.
리소스 및 추가 자료
이미지 크레디트: Mael BALLAND
원래 내 blog에 게시되었습니다. 더 많은 숨겨진 보석을 보려면 Twitter에서 저를 팔로우하세요.
Reference
이 문제에 관하여(몇 분 만에 React + TypeScript + Tailwind + 클래스 이름 시작하기), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/okeeffed/getting-started-with-react-typescript-tailwind-classnames-in-minutes-1j4l텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)