react結(jié)合typescript?封裝組件實(shí)例詳解
項(xiàng)目環(huán)境搭建
項(xiàng)目依賴
創(chuàng)建支持 TypeScript 的 React 項(xiàng)目
npx create-react-app my-demo --template typescript
根據(jù) typescript 官網(wǎng)文檔的說明,還可以使用下面的命令
npx create-react-app my-demo --scripts-version=react-scripts-ts
css樣式初始化的插件
npm install --save normalize.css
處理scss文件
npm install node-sass --save
一個(gè)簡(jiǎn)單的、有條件的綁定多個(gè) className 的 JavaScript 實(shí)用函數(shù)
npm install classnames
@types 支持全局和模塊類型定義
npm install @types/classnames --save
項(xiàng)目目錄結(jié)構(gòu)
my-demo |—— node_modules |—— public | └─ favicon.ico | └─ index.html | └─ manifest.json |—— src | └─ ... |─ .gitignore |─ package.json |─ package-lock.json |─ README.md └─ tsconfig.json //文件中指定了用來編譯這個(gè)項(xiàng)目的根文件和編譯選項(xiàng)
創(chuàng)建一個(gè)組件
在項(xiàng)目中 刪除src目錄下除src/index.tsx之外所有的文件
import React from 'react';
import ReactDOM from 'react-dom/client';
import Hello from './src/Hello'
const root = ReactDOM.createRoot(
document.getElementById('root') as HTMLElement
);
root.render(
<div>hellow TS</div>
);
在src下創(chuàng)建 Hello.tsx文件
import React form 'react'
//聲明 Hello 組件 props 接口類型
interface BaseProps {
message?:string //可選填 string 類型
}
const Hello:FunctionComponent<BaseProps> =(props) => {
/*
FunctionComponent<BaseProps> 接口,接收一個(gè)泛型
+ 使用 interface 定義的 BaseProps j接口作為泛型值
+ 組件還可以接收 props.chilren 屬性接收組件實(shí)例傳入的子節(jié)點(diǎn)
+ 使用 defaultProps 為 props 對(duì)象中屬性設(shè)置初始化值
+ React.FunctionComponent 可以簡(jiǎn)寫為 const Hello: FC<BaseProps> = (props) => {}
*/
return <h1>{props.message}</h1>
}
在終端執(zhí)行 npm start啟動(dòng)項(xiàng)目查看結(jié)果
封裝一個(gè)Button組件
Button按鈕需求分析

依賴
classnames: 一個(gè)簡(jiǎn)單的 JavaScript 實(shí)用程序,用于有條件地將 classNames 連接在一起
$ npm install classnames --save
$ npm install @types/classnames --save //@types 支持全局和模塊類型定義
用于編譯css
npm install node-sass --save
classnames 使用示例
/* 與Node.js、Browserify或webpack 一起使用: */
var classNames = require('classnames');
classNames('foo', 'bar'); // => 'foo bar'
classNames('foo', 'bar'); // => 'foo bar'
classNames('foo', { bar: true }); // => 'foo bar'
classNames({ 'foo-bar': true }); // => 'foo-bar'
classNames({ 'foo-bar': false }); // => ''
classNames({ foo: true }, { bar: true }); // => 'foo bar'
classNames({ foo: true, bar: true }); // => 'foo bar'
/* // lots of arguments of various types */
classNames('foo', { bar: true, duck: false }, 'baz', { quux: true }); // => 'foo bar baz quux'
// other falsy values are just ignored
classNames(null, false, 'bar', undefined, 0, 1, { baz: null }, ''); // => 'bar 1'
/* 與 React.js 一起使用 */
/* 這個(gè)包是 的官方替代品classSet,它最初是在 React.js 插件包中提供的。
它的主要用例之一是使動(dòng)態(tài)和條件className道具更易于使用(尤其是比條件字符串操作更簡(jiǎn)單)。因此,您可能有以下代碼來className為<button>React 中的a生成道具: */
class Button extends React.Component {
// ...
render () {
var btnClass = 'btn';
if (this.state.isPressed) btnClass += ' btn-pressed';
else if (this.state.isHovered) btnClass += ' btn-over';
return <button className={btnClass}>{this.props.label}</button>;
}
}
/* 您可以將條件類更簡(jiǎn)單地表示為一個(gè)對(duì)象: */
var classNames = require('classnames');
class Button extends React.Component {
// ...
render () {
var btnClass = classNames({
btn: true,
'btn-pressed': this.state.isPressed,
'btn-over': !this.state.isPressed && this.state.isHovered
});
return <button className={btnClass}>{this.props.label}</button>;
}
}
/*因?yàn)槟梢詫?duì)象、數(shù)組和字符串參數(shù)混合在一起,所以支持可選的classNameprops 也更簡(jiǎn)單,因?yàn)榻Y(jié)果中只包含真實(shí)的參數(shù): */
var btnClass = classNames('btn', this.props.className, {
'btn-pressed': this.state.isPressed,
'btn-over': !this.state.isPressed && this.state.isHovered
});
在src新建components/Button/buttom.tsx組件
import React,{ ButtonHTMLAttributes, AnchorHTMLAttributes, FC } from 'react'
import classNames form 'classnames'
//聲明按鈕尺寸-枚舉
export enum ButtonSize {
Large = 'lg',
Small = 'sm'
}
//聲明按鈕樣式-枚舉
export enum ButtonType{
Primary = 'primary',
Default = 'default',
Danger = 'danger',
Link = 'link'
}
//聲明按鈕組件 props 接口
interface BaseButtonProps {
className?: string;
/*設(shè)置 Button的禁用*/
disabled?:boolean;
/*設(shè)置 Button的尺寸*/
size?:ButtonSize;
/*設(shè)置 Button 的類型*/
btnType?:ButtonType;
children: React.ReactNode; //ReactNode reactnode節(jié)點(diǎn)
/*設(shè)置A標(biāo)簽href的類型*/
href?:string;
}
//聲明按鈕與超鏈接標(biāo)簽的原生事件
type NativeButtonProps = BaseButtonProps & ButtonHTMLAttributes<HTMLElement>
type AnchorButtonProps = BaseButtonProps & AnchorHTMLAttributes<HTMLElement>
export type ButtonProps = Partial<NativeButtonProps & AnchorButtonProps>
export conast Button:FC<ButtonProps> = (props) =>{
const {
btnType, //傳遞進(jìn)來按鈕樣式屬性
className, //傳遞進(jìn)來自定義樣式屬性
disabled, //傳遞進(jìn)來是否禁用屬性
size,
children,
href,
...restProps //解析按鈕與超鏈接的原生事件屬性
} = props;
/*樣式拼接處理*/
const classes = classNames('btn', className, {
/*[`btn-${btnType}`] : boolean
boolean:
+ 為真返回 [`btn-${btnType}`]
+ 為假 不返回任何內(nèi)容
*/
[`btn-${btnType}`]: btnType,
[`btn-${size}`]:size,
'disabled':(btnType === 'link') && disabled //如果傳遞btnType的屬性值為link并設(shè)置disabled屬性,按鈕就是禁用狀態(tài)。
});
if(btnType === "link" && href){
return (
<a
className={classes}
href={href}
{...restProps} //解析按鈕與超鏈接的原生事件屬性
>
{children}
</a>
)
}else{
return(
<button
className={classes}
disabled={disabled}
{...restProps}
>
{children}
</button>
)
}
}
/*定義 props 的默認(rèn)值*/
Button.defaultProps = {
disabled:false,
btntype:ButtonType.Default,
btntype:ButtonSize.Large,
}
export default Button;
添加默認(rèn)樣式
npm install --save normalize.css
在src目錄先新建styles文件夾,在styles文件夾下新建index.css | index.scss文件
在styles/index.css文件中引入normalize.css & components/Button/buttom.css
在src/index.tsx文件中引入styles/index.css
import React from 'react';
import ReactDOM from 'react-dom/client';
import './styles/index.scss'
import App from './App';
const root = ReactDOM.createRoot(
document.getElementById('root') as HTMLElement
);
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
在src新建components/Button/buttom.css | buttom.scss組件
.btn {
position: relative;
display: inline-block;
font-weight: 400;
line-height: 1.5;
white-space: nowrap;
text-align: center;
vertical-align: middle;
background-image: none;
border: 1px solid transparent;
border-radius: 0.25rem;
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.15), 0 1px 1px rgba(0, 0, 0, 0.075);
transition: color 0.15s ease-in-out, background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
cursor: pointer;
}
.btn-danger {
color: #fff;
background: #dc3545;
border-color: #dc3545;
}
.btn-primary {
color: #fff;
background: #0d6efd;
border-color: #0d6efd;
}
.btn-lg {
padding: 0.5rem 1rem;
font-size: 1.25rem;
border-radius: 0.3rem;
}
.btn-sm {
padding: 0.25rem 0.5rem;
font-size: 0.875rem;
border-radius: 0.2rem;
}
.btn-xxx {
width:200px;
height:200px;
}
.btn-link {
font-weight: 400;
color: #0d6efd;
text-decoration: none;
box-shadow: none;
}
.disabled,
.btn[disabled]{
cursor: not-allowed;
opacity: 0.65;
box-shadow: none;
}
在scr/App.tsx組件中引入Button組件
import React from 'react';
// 導(dǎo)入Button 組件
import Button,{ButtonType,ButtonSize} from './conponents/Button/button';
/*Button組價(jià)可選屬性
組件類型
ButtonType.Primary = 'primary'
ButtonType.Default = 'default'
ButtonType.Danger = 'danger'
ButtonType.Link = 'link'
組件大小
ButtonSize.Large = 'lg'
ButtonSize.Small = 'sm'
*/
function App() {
return (
<div className="App">
<Button autoFocus>Hello</Button>
<Button className='btn-xxx'>Hello</Button>
<Button disabled>Disabled Button</Button>
<Button btnType={ButtonType.Primary} size={ButtonSize.Large}>Primary-Lrage-Button</Button>
<Button btnType={ButtonType.Danger} size={ButtonSize.Small}>Danger-Small-Button</Button>
<Button btnType={ButtonType.Link} disabled>被禁用的按鈕</Button>
<Button btnType={ButtonType.Link} target='target'>在新窗口打開</Button>
</div>
);
}
export default App;
在當(dāng)前項(xiàng)目終端組輸入npm start啟動(dòng)項(xiàng)目查看結(jié)果


以上就是react結(jié)合typescript 封裝組件實(shí)例詳解的詳細(xì)內(nèi)容,更多關(guān)于react typescript 封裝組件的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
- 基于TypeScript 的React 項(xiàng)目創(chuàng)建
- TypeScript在React項(xiàng)目中的實(shí)戰(zhàn)應(yīng)用指南及技巧
- React使用TypeScript的最佳實(shí)踐和技巧
- ReactJS中使用TypeScript的方法
- React+Typescript創(chuàng)建項(xiàng)目的實(shí)現(xiàn)步驟
- TypeScript在React中的應(yīng)用技術(shù)實(shí)例解析
- React+umi+typeScript創(chuàng)建項(xiàng)目的過程
- React中常見的TypeScript定義實(shí)戰(zhàn)教程
- 使用?TypeScript?開發(fā)?React?函數(shù)式組件
- TypeScript結(jié)合React的使用指南
相關(guān)文章
React?高德地圖進(jìn)京證路線規(guī)劃問題記錄(匯總)
這篇文章主要介紹了React高德地圖進(jìn)京證路線規(guī)劃問題小記,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧2024-08-08
react源碼中的生命周期和事件系統(tǒng)實(shí)例解析
這篇文章主要為大家介紹了react源碼中的生命周期和事件系統(tǒng)實(shí)例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-01-01
react-native中ListView組件點(diǎn)擊跳轉(zhuǎn)的方法示例
ListView作為React Native的核心組件,用于高效地顯示一個(gè)可以垂直滾動(dòng)的變化的數(shù)據(jù)列表。下面這篇文章主要給大家介紹了關(guān)于react-native中ListView組件點(diǎn)擊跳轉(zhuǎn)的相關(guān)資料,需要的朋友可以參考借鑒,下面來一起看看吧。2017-09-09
Ant Design與Ant Design pro入門使用教程
Ant Design 是一個(gè)服務(wù)于企業(yè)級(jí)產(chǎn)品的設(shè)計(jì)體系,組件庫是它的 React 實(shí)現(xiàn),antd 被發(fā)布為一個(gè) npm 包方便開發(fā)者安裝并使用,這篇文章主要介紹了Ant Design與Ant Design pro入門,需要的朋友可以參考下2023-12-12
React項(xiàng)目使用ES6解決方案及JSX使用示例詳解
這篇文章主要為大家介紹了React項(xiàng)目使用ES6解決方案及JSX使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12
基于Cloud?Studio構(gòu)建React完成點(diǎn)餐H5頁面(騰訊云?Cloud?Studio?實(shí)戰(zhàn)訓(xùn)練營)
最近也是有機(jī)會(huì)參與到了騰訊云舉辦的騰訊云Cloud Studio實(shí)戰(zhàn)訓(xùn)練營,借此了解了騰訊云Cloud?Studio產(chǎn)品,下面就來使用騰訊云Cloud?Studio做一個(gè)實(shí)戰(zhàn)案例來深入了解該產(chǎn)品的優(yōu)越性吧,感興趣的朋友跟隨小編一起看看吧2023-08-08

