react相关知识

时间:2021-02-01 13:01:02   收藏:0   阅读:0

1、要想在项目中使用json格式数据,

import Robot from "./components/Robot";
需要在tsconfig文件中打开这两个配置:

"moduleResolution": "node",
"resolveJsonModule": true,

2 函数式组件 React.FC 的含义

React.FC表示 functional component 函数式组件的接口 interface
FC表示type React.FC<P = {}> = React.FunctionComponent<P>
其中范性参数P表示props

const Robot: React.FC<RobotProps> = ()=>{}

3、引入CSS文件

import ‘./index.css‘;
<div className="app"></div>
declare module "*.css" {
  const css: { [key: string]: string };
  export default css;
}
function App() {
  return (
    <div className={style.list}>xxx</div>
  );
}

使用ts提示功能,让模块化引入的css也有提示功能

<div className={style.这里会提示css文件中的样式}></div>
"devDependencies": {
    "typescript-plugin-css-modules": "^2.8.0"
}
"plugins": [
    {
    "name": "typescript-plugin-css-modules"
    }
]
{
	"typescript.tsdk": "node_modules/typescript/lib",
	"typescript.enablePromptUseWorkspaceTsdk": true
}

如何获取事件中e的类型?

比如下面,把光标放在onClick上,就会出现提示:
(event:React.MouseEvent<HTMLButtonElement,MouseEvent >)

<button onClick={this.handleClick}>
</button>

event事件

点击购物车 2 (件):
e.target:描述的是事件发生的元素:<span>购物车2(件)</span>
e.currentTarget :描述的是事件处理绑定的元素:<button class>...</button>

例如:

handleClick = (e:React.MouseEvent<HTMLButtonElement, MouseEvent>) => {
console.log("e.target ", e.target)
console.log("e.currentTarget ", e.currentTarget)
}
<button
    className={styles.button}
    onClick={this.handleClick}
>
    <FiShoppingCart />
    <span>购物车 2 (件)</span> 
</button>

使用类型断言限制点击的元素

if((e.target as HTMLElement).nodeName === "SPAN"){
    this.setState({ isOpen: !this.state.isOpen });
}
componentDidMount() {
fetch("https://jsonplaceholder.typicode.com/users")
    .then((response) => response.json())//response.json() 返回主体
    .then((data) => this.setState({ robotGallery: data }));
}

react生命周期

技术图片

Hooks

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!