AntDesign(React)学习-15 组件定义、connect、interface

虽然常用的编码用一种即可,但是看别人文档或者示例时,有的写法不熟悉的话看着很不习惯,整理几种实现同一功能的不同写法

1、Dva Connect与@Connect

import React, { Props } from 'react';
import { Button, Input } from 'antd';
import { connect } from 'dva';
//@connect(()=>({"age":111}))
class Demo extends React.Component {
  constructor(props) {
    super(props);
  }
  render(){

    return(<div>{this.props.age}</div>);
  }
}
//export default Demo;
export default connect(()=>({"age":111}))(Demo);
//大括号被解释伪代码块,所以如果箭头函数直接返回一个对象,必须在对象外边加上括号,类似一个转义,箭头函数本身默认return

箭头函数:仅仅当箭头函数为单行的形式时,才会出现隐式的return。当箭头函数伴随着{}被声明,那么即使它是单行的,它也不会有隐式return

有篇讲的全的:https://www.cnblogs.com/mengff/p/9656486.html

2、组件定义,主要三种,示例

class Test extends Component {
function Test(props) {
class Test extends PureComponent {
function Test<P>(params?: any){
const Test: React.FC<TestProps> = (props) => {

参考下面两个链接文章

https://www.jianshu.com/p/2d00885a6d59

https://www.cnblogs.com/V587Chinese/p/11520674.html

3、props属性红色下划线,使用typescript的话,interface用于限定props属性,如果不使用interface的话会有很多红下划线,看着很刺眼
 以比较复杂的Redux中的dispatch为例,

方法一:声明interface

import { AnyAction } from 'redux';
export interface UserProps extends Dispatch<AnyAction> {
  dispatch: Dispatch<AnyAction>;
}
class User extends React.Component<UserProps> 
.......

通过以上三个步骤可解决红线问题

方法二:

(props as any).dispatch

posted @ 2020-02-13 00:01  zhaogaojian  阅读(5502)  评论(0编辑  收藏  举报