组件化拆分,易于复用、扩展、维护。
- 父子组件传参使用属性
- 子组件使用PropTypes进行类型校验
- 子组件调用父组件方法
- 默认属性设置
// Demo
import React, { Component, Fragment } from 'react';
import DemoItem from './DemoItem';
class Demo extends Component<any, any> {
// 构造函数
constructor(props: any) {
super(props);
// 数据绑定
this.state = {
msg: 'Hello World, This is Demo Template!',
value: '',
data: []
};
}
// 双向数据绑定
public changeValue(e: any): void {
this.setState({
value: e.target.value,
});
}
// 添加
public addValue(): void {
this.setState({
data: [...this.state.data, this.state.value],
value: '',
});
}
// 删除
public deleteItem(i: number): void {
let data: any = this.state.data;
data.splice(i, 1);
this.setState({
data: data,
})
}
public render(): any {
return (
// 代码注释方式
<Fragment>
{/*代码注释方式*/}
<div className="">
<span>{ this.state.msg }</span>
<button onClick={() => this.props.history.push('/')}>返回</button>
</div>
<div className="">
<label htmlFor="addValue">请输入:</label>
<input type="text" id="addValue" value={ this.state.value } onChange={e => this.changeValue(e)} />
<button onClick={() => this.addValue()}>添加</button>
<ul>
{
this.state.data.map((item: string, index: number) => {
return (
// 父组件向子组件传值
<DemoItem content={ item } deleteItem={() => this.deleteItem(index)} key={ index + item } />
)
})
}
</ul>
</div>
</Fragment>
);
}
}
export default Demo;
// DemoItem
import React, {Component, Fragment} from 'react';
import PropTypes from 'prop-types';
class DemoItem extends Component<any, any> {
public static propsTypes: { content: PropTypes.Validator<string>; deleteItem: PropTypes.Requireable<(...args: any[]) => any>; };
public static defaultProps: { msg: string; };
// 构造函数
constructor(props: any) {
super(props);
this.state = {};
}
// 子组件调用父组件方法
public handleClick(): void {
this.props.deleteItem();
}
public render(): any {
return (
<Fragment>
{/*dangerouslySetInnerHTML 用于解析html*/}
<li dangerouslySetInnerHTML={{__html: this.props.content}} onClick={() => this.handleClick()} />
</Fragment>
);
}
}
// 类型校验
DemoItem.propsTypes = {
content: PropTypes.string.isRequired,
deleteItem: PropTypes.func,
};
// 默认属性
DemoItem.defaultProps = {
msg: 'Default Props',
};
export default DemoItem;