React TS 組件 Demo


無狀態組件

例子:點擊查看大圖

import React, { MouseEvent, SFC } from 'react'

type Props = {
  onClick(e: MouseEvent<HTMLElement>): void
  src: string,
  show: boolean,
}

const BigImage: SFC<Props> = ({ onClick, show, src }) => {
  return show ? <div className="big-img-wrap" onClick={onClick}>
      <div className="big-img-content">
        <img src={src} className="big-img"} alt="" />
      </div>
  </div> : null;
}

export default IMBigImage;

參數完全由父容器提供,樣式如下

.big-img-wrap {
  position: absolute;
  overflow: hidden;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, .65);
  z-index: 10;
}
.big-img-content {
  position: absolute;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  top: 10%;
  left: 10%;
  bottom: 10%;
  right: 10%;
  background: #FFF;
  border-radius: 8px;
  overflow: hidden;
}
.big-img {
  max-width: 100%;
  max-height: 100%;
  vertical-align: top;
}

有狀態組件

例子:按鈕點擊計數

import React, { Component } from 'react';

import { Button } from 'antd';

type IProps = Readonly<{
  className?: string;
  style?: React.CSSProperties;
  value?: string;
  onChange?: Function;
}>;

const initialState = { clickCount: 0 };
type IState = Readonly<typeof initialState>;

class ButtonCounter extends Component<IProps, IState> {
  readonly state: IState = initialState;
  
  componentWillReceiveProps(nextProps: any) {
    const { value } = nextProps;
    if (value) {
      this.setState({
        clickCount: value
      })
    }
  }

  render() {
    const { clickCount } = this.state;
    const { className, style } = this.props;
    return (
      <div className={`${className}`} style={`${style}`}>
        <Button onClick={this.handleIncrement}>Increment</Button>
        <Button onClick={this.handleDecrement}>Decrement</Button>
        You've clicked me {clickCount} times!
      </div>
    );
  }

  private handleIncrement = () => {
    const { onChange } = this.props;
    const { clickCount } = this.state;
    this.setState({
      clickCount: clickCount + 1,
    });  
    onChange && onChange(clickCount + 1);
  };
  private handleDecrement = () => {
    const { onChange } = this.props;
    const { clickCount } = this.state;
    this.setState({
      clickCount: clickCount - 1,
    });  
    onChange && onChange(clickCount - 1);
  }
}

支持從父容器傳遞樣式更改。

使用 componentWillReceiveProps 是為了能把父組件的 value 同步給子組件。完整的組件數據傳遞就該是 父傳子,觸發子的 componentWillReceiveProps 來同步數據,然后操作子更改狀態並把動作傳給父。

使用了 Readonly 將 IProps 和 IState 設為只讀,是為了防止其他函數里改動它們。

參考

TypeScript 2.8下的終極React組件模式


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM