美文网首页
创建ts react项目

创建ts react项目

作者: Nick_4438 | 来源:发表于2022-07-02 20:29 被阅读0次

创建项目

npm install -g create-react-app
npx create-react-app my-app --template typescript
cd my-app

启动项目

npm install
npm run start 

访问:http://localhost:3000/ 测试页面

  • 编译项目
npm run build 

创建组件

  • 创建组件 文件夹src/componennt/Hello.tsx
import React from "react";
const Hello: React.FC = () => {
  return <div>
    hello
  </div>
}
export default Hello;
  • 引用组件
import React from 'react';
import logo from './logo.svg';
import './App.css';
import Hello from './component/Hello';

function App() {
  return (
    <div className="App">
      <Hello ></Hello>
      启动
    </div>
  );
}

export default App;

组件参数传递

import React from "react";


interface ShoppingListParam {
  name: string;
  click?: () => void
}

const ShoppingList: React.FC<ShoppingListParam> = (param: ShoppingListParam) => {
  const { name, click } = param;
  const apps = ["Instagram", "WhatsApp", "Oculus"];
  return (
    <div className="shopping-list" onClick={() => {
      if (click)
        click();
    }}>
      <h1>Shopping List for {name}</h1>
      <ul>
        {
          apps.map((v, index) => {
            return <li key={index}>{v}</li>
          })
        }
      </ul>
    </div>
  );

}
export default ShoppingList;

// 用法示例: <ShoppingList name="Mark" />

浏览器调试工具

Chrome 或者 Firefox 中安装扩展 React Devtools 可以让你在浏览器开发者工具中查看 React 的组件树。

image.png

相关文章

网友评论

      本文标题:创建ts react项目

      本文链接:https://www.haomeiwen.com/subject/ysvkbrtx.html