ts和react的默认属性的四种解决方案

  • Non-null assertion operator(非空断言语句)
  • Component type casting(组件类型重置)
  • High order function for defining defaultProps(高阶组件)
  • Props getter function(Getter函数)

1、 非空断言语句

1、const color = this.props.color!;
2、this.props.onBlur ? this.props.onBlur(e): undefined;

2、组件类型重置

以通过匿名类创建组件,并将其分配给常量,我们将使用适当的道具类型将其转换为最终结果组件,同时保留实现中定义的所有“defaultProps”

3、高阶组件

globals.d.ts

declare type Omit<T, K> = Pick<T, Exclude<keyof T, K>>

在uitls中定义withDefaultProps

export const withDefaultProps = <P extends object, DP extends Partial<P> = Partial<P>>(
defaultProps: DP,
Cmp: React.ComponentType<P>
) => {
type RequiredProps = Omit<P, keyof DP>
type Props = Partial<DP> & RequiredProps
Cmp.defaultProps = defaultProps
return (Cmp as React.ComponentType<any>) as React.ComponentType<Props>
}

说明

使用上面或者下面的实现都可以

input组件为一个完整的例子:

import classnames from 'classnames';
import * as React from 'react';
import { withDefaultProps } from '../utils';
import './style/input.styl'; const defaultProps = {
type: 'text',
value: '',
disabled: false,
readonly: false,
maxlength: 60,
placehololder: '',
autofocus: false,
autocomplete: '',
clearable: false,
passShow: false
} type DefaultProps = Readonly<typeof defaultProps>; type InputInnerProps = {
prepend?: React.ReactNode;
append?: React.ReactNode;
className?: string;
style?: React.CSSProperties;
onChange?: (value: string) => void;
onBlur?: (e: React.FocusEvent<HTMLInputElement>) => void;
onFocus?: (e: React.FocusEvent<HTMLInputElement>) => void;
} & DefaultProps; const InputState = {
isFocus: false,
inputValue: '',
open: false
}; type State = Readonly<typeof InputState>; const Input = withDefaultProps(
defaultProps,
class extends React.Component<InputInnerProps, State> {
readonly state: State = InputState;
private inputRef: React.RefObject<any> = React.createRef();
getDerivedStateFromProps() {
this.setState({
open: this.props.passShow,
inputValue: this.props.value
})
} private changeHander = (e: React.ChangeEvent<HTMLInputElement>):void => {
this.setState({
inputValue: e.target.value
})
this.props.onChange ? this.props.onChange(e.target.value) : undefined;
}
private handleFoucus = (e: React.FocusEvent<HTMLInputElement>):void => {
this.props.onFocus ? this.props.onFocus(e): undefined;
this.setState({
isFocus: true
})
}
private handleBlur = (e: React.FocusEvent<HTMLInputElement>):void => {
this.props.onBlur ? this.props.onBlur(e): undefined;
this.setState({
isFocus: true
})
}
private handleClear = ():void => {
this.setState({
inputValue: ''
})
this.inputRef.current.focus();
}
private handlePwdEye = ():void => {
this.setState({
open: !this.state.open
})
}
public render() {
const {
type,
disabled,
readonly,
autocomplete,
autofocus,
clearable,
passShow,
className,
style,
prepend,
append,
...restProps
} = this.props;
const {
isFocus,
inputValue,
open
} = this.state;
const inputCls = classnames('afo-input', className, {
'afo-input--active': isFocus
})
const inputType:string = type === 'password' && passShow ? 'text': type;
const showClear:boolean = clearable && inputValue && !readonly && !disabled ? true: false;
const showPwdEye:boolean = type === 'password' && passShow && !disabled ? true: false;
return (
<div className={inputCls} style={style}>
{
prepend ? <div className="afo-input__prepend">{prepend}</div> : ''
}
<input
className="afo-input__field"
ref={this.inputRef}
value={inputValue}
{...restProps}
type={inputType}
disabled={disabled}
readOnly={readonly} autoComplete={autocomplete}
autoFocus={autofocus}
onFocus={(e) => this.handleFoucus(e)}
onBlur={(e) => this.handleBlur(e)}
onChange={(e) => this.changeHander(e)}
/>
{
append || showClear || showPwdEye?
<div className="afo-input__append">
{
showClear ? <div className="afo-input__clear" onClick={() => this.handleClear()}>
<i className="afo-wrong" />
</div> : ''
}
{
showPwdEye ?
<div className="afo-input__eye" onClick={() => this.handlePwdEye()}>
<i className={open ? 'afo-inupt__eye--visible' : 'afo-inupt__eye--invisible'} />
</div> : ''
}
{append}
</div> :''
}
</div>
)
}
}
) export default Input;

4、Props getter function

条件类型映射的简陋工厂/闭包标识函数模式。

注意,我们使用了与withDefaultProps函数类似的类型映射构造,但我们不将defaultProps映射为可选的,因为它们在组件实现中是不可选的。





TypeScript 3.0下react默认属性DefaultProps解决方案的更多相关文章

  1. IE10-IE11在NET4.0下出现“__doPostBack未定义”解决方案

    IE10在NET4.0下出现"__doPostBack未定义"的办法 参考文章: http://blogs.msdn.com/b/scott_hanselman/archive/2 ...

  2. React 学习(二) ---- props验证与默认属性

    在上一节中, 我们提到了props, 组件之间数据的传递使用props. 我们调用组件时可以设置props, 组件内部通过props获取. 为了props 使用更加友好, React 提供了简单的验证 ...

  3. 关于div容器在ie6下默认高度不为0(存在默认高度)

    最近做项目的时候遇到一个问题,相信很多人都遇到过,就是在测试兼容性的时候,在ie6下小于12px 的背景的高度不等于原高,或许这样说你可能不是很明白,那就举个例子吧! 如图所示: 锯齿状的背景图本来是 ...

  4. CDH 6.0.1 版本 默认配置下 HUE | happybase 无法访问 Hbase 的问题

    第一个问题 HUE 无法直接连接到 HBase 在默认配置下 CDH 6.0.1 版本下的 HBase2.0 使用了默认配置 hbase.regionserver.thrift.compact = T ...

  5. React组件属性部类(propTypes)校验

    React组件属性类型(propTypes)校验 Prop 验证 随着应用不断变大,保证组件被正确使用变得非常有用.为此我们引入propTypes.React.PropTypes 提供很多验证器 (v ...

  6. 在 Typescript 2.0 中使用 @types 类型定义

    在 Typescript 2.0 中使用 @type 类型定义 基于 Typescript 开发的时候,很麻烦的一个问题就是类型定义.导致在编译的时候,经常会看到一连串的找不到类型的提示.解决的方式经 ...

  7. Vue.js 2.0 和 React、Augular

    Vue.js 2.0 和 React.Augular 引言 这个页面无疑是最难编写的,但也是非常重要的.或许你遇到了一些问题并且先前用其他的框架解决了.来这里的目的是看看Vue是否有更好的解决方案.那 ...

  8. 使用Typescript重构axios(十五)——默认配置

    0. 系列文章 1.使用Typescript重构axios(一)--写在最前面 2.使用Typescript重构axios(二)--项目起手,跑通流程 3.使用Typescript重构axios(三) ...

  9. TypeScript 2.0开启空值的严格检查

    摘要:在编程过程成空指针是最常见的bug之一,但是在TypeScript中我们无法使用具体的类型来表示特定的变量不能为空!幸运的是,TypeScript 2.0 解决了这个问题. 本文分享自华为云社区 ...

随机推荐

  1. computed--实时计算属性

    项目:https://github.com/ccyinghua/vue-node-mongodb-project/blob/master/07-shoppingCart.md 实时计算属性的compu ...

  2. Mysql url参数浅析

    驱动包用的是mysql-connector-java-8.0.11.jar 新版的驱动类改成了com.mysql.cj.jdbc.Driver //北京时间东八区 serverTimezone=GMT ...

  3. JavaScript变量不同类型之间的自动、手动类型转换

    转换成字符型:toString() var str = 123; str.toString();转换成字符串 将str从数值型变成字符型       浮点数:         电脑在运算过程中以正确的 ...

  4. gd库 给底图写入文字问题

    png-8的图片 设置颜色会返回false,换成png-24的就可以了

  5. django+xadmin在线教育平台(十二)

    6-4 用form实现登录-1 上面我们的用户登录的方法是基于函数来做的.本节我们做一个基于类方法的版本. 要求对类的继承有了解. 基础教程中基本上都是基于函数来做的,其实更推荐基于类来做.基于类可以 ...

  6. 汇编:输出寄存器AX中的内容

    DATAS segment Temp db '0000H','$' DATAS ends CODES segment START: mov AX,DATAS mov DS,AX ;正式代码开始 mov ...

  7. PHP提取奇数或偶数下标元素

    该功能主要用到 array_filter() 函数,这个函数可以用回调函数过滤数组中的单元.用法: array array_filter ( array $array [, callable $cal ...

  8. &、|、~与&&、||、! 谬误

    按位运算符(&.|.~)的操作是被默认为一个二进制的位序列,分别对其中的每个位进行操作. 逻辑运算符(&&.||.!)将操作数当成非真及假,非假及真.通常就是将0当成假,非0即 ...

  9. PLC状态机编程-如何在STL中使用状态机

    搞PLC编程多年,一直不知道状态机,学习matlab后,发现状态机编程异常方便,过去很多编程时的疑惑豁然开朗起来.今天跟大家分享一下如何在STL中使用状态机. 下面是用状态机描述的控制任务. 这个状态 ...

  10. VIM配置IDE

    转载于:https://blog.csdn.net/andre617/article/details/53496490#%E8%84%9A%E6%B3%A8 由于YCM需要vim支持python,需要 ...