顾轩 發表於 2020-3-18 17:41:00

React TS 组件 Demo

<h2 id="无状态组件">无状态组件</h2>
<p>例子:点击查看大图</p>
<pre><code>import React, { MouseEvent, SFC } from 'react'

type Props = {
onClick(e: MouseEvent&lt;HTMLElement&gt;): void
src: string,
show: boolean,
}

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

export default IMBigImage;
</code></pre>
<p>参数完全由父容器提供,样式如下</p>
<pre><code class="language-css">.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;
}
</code></pre>
<h2 id="有状态组件">有状态组件</h2>
<p>例子:按钮点击计数</p>
<pre><code>import React, { Component } from 'react';

import { Button } from 'antd';

type IProps = Readonly&lt;{
className?: string;
style?: React.CSSProperties;
value?: string;
onChange?: Function;
}&gt;;

const initialState = { clickCount: 0 };
type IState = Readonly&lt;typeof initialState&gt;;

class ButtonCounter extends Component&lt;IProps, IState&gt; {
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 (
      &lt;div className={`${className}`} style={`${style}`}&gt;
      &lt;Button onClick={this.handleIncrement}&gt;Increment&lt;/Button&gt;
      &lt;Button onClick={this.handleDecrement}&gt;Decrement&lt;/Button&gt;
      You've clicked me {clickCount} times!
      &lt;/div&gt;
    );
}

private handleIncrement = () =&gt; {
    const { onChange } = this.props;
    const { clickCount } = this.state;
    this.setState({
      clickCount: clickCount + 1,
    });
    onChange &amp;&amp; onChange(clickCount + 1);
};
private handleDecrement = () =&gt; {
    const { onChange } = this.props;
    const { clickCount } = this.state;
    this.setState({
      clickCount: clickCount - 1,
    });
    onChange &amp;&amp; onChange(clickCount - 1);
}
}
</code></pre>
<p>支持从父容器传递样式更改。</p>
<p>使用 componentWillReceiveProps 是为了能把父组件的 value 同步给子组件。完整的组件数据传递就该是 父传子,触发子的 componentWillReceiveProps 来同步数据,然后操作子更改状态并把动作传给父。</p>
<p>使用了 Readonly 将 IProps 和 IState 设为只读,是为了防止其他函数里改动它们。</p>
<h2 id="参考">参考</h2>
<p>TypeScript 2.8下的终极React组件模式</p><br><br>
来源:https://www.cnblogs.com/everlose/p/12518852.html
頁: [1]
查看完整版本: React TS 组件 Demo