React 进阶之选择合适的组件类型

4,456 阅读4分钟

最近项目基本都是用 React,今天总结分享 React Component 常见的几种形式,如果你在写 React 时经常不知道怎么拆分代码,这篇文章或许对你有所帮助。

原文链接: w3ctrain.com/2018/11/05/…

为了更充分理解 React,先搞懂平时写的 JSX 是什么。初学的时候有比较大困惑,这是一门新语言吗?大部分人是匆匆扫过文档就开始开发。通过 babel-presets-react 处理能看到,其实 JSX 只是语法糖,最终在浏览器跑的还是 JS。React Component 最终都通过 React.createElement 创建。总之,写 React 其实就是在写 JS

jsx

SFC (Stateless Functional Component)

React 可以使用 Function 来创建 Component,这类 Component 没有 lifecycle, 内部不维护 state,只要传入的 props 有变化则进行重新渲染。

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

用箭头函数的写法还更加简洁。

const Welcome = props => <h1>Hello, {props.name}</h1>;

上面两种形式生成 es5 代码都是一样的。

var Welcome = function Welcome(props) {
  return _react2.default.createElement(
    "h1",
    null,
    "Hello, ",
    props.name
  );
};

SFC 的特点是纯粹只做 render,代码简短没有其他条件分支,并且相比 class Component 编译后的代码量会少一些。

尴尬的是,在 React 16.7 react hooks 出来之后,SFC 这个名字有歧义了,因为用上 useState,SFC 也可以有 local state, 同样可以拥有 lifecycle。再称之为 Stateless Components 就很尴尬,改名叫 FC ?

HOC (Higher-Order Components)

高阶组件对于 Vue 开发者来说应该是个陌生的概念(不知道,我用 Vue 的时候没见过类似的用法)。从代码上看,高阶组件就是一个方法,传入一个组件,返回另一个组件。

function logProps(WrappedComponent) {
  return class extends React.Component {
    componentWillReceiveProps(nextProps) {
      console.log('Current props: ', this.props);
      console.log('Next props: ', nextProps);
    }
    render() {
      return <WrappedComponent {...this.props} />;
    }
  }
}

最常见的高阶组件是 react-redux 里面的 connect 方法,通过传入 组件和 map*ToProps 方法,让组件和 store 连接。组件内部就可以直接通过 props 获得 connect 之后的值。

exprot default connect(
  mapStateToProps,
  mapDispatchToProps,
)(Component);

高阶组件适合用来扩展功能,把这部分功能从业务组件中抽离出来,需要的套上,不需要的时候移除,对被包裹组件侵入性非常小。

Dynamic Component

有些业务场景下,在执行时才能确定具体的标签或者组件是什么。在 React 的世界里面,以大写字母开头会被当成动态组件加载,而小写字母开头会被认为是 HTML DOM tag。

// Heading.js
render() {
    const { tag: Tag, children } = this.props;
    return <Tag>{ children }</Tag>
}

根据万物皆为 JS 理论,只要传入不同的 tag 标签,就会渲染出不同的 heading 标签。

heading

我们常用这种方式,在后端配置组件和数据,前端读取配置之后渲染出对应的内容。

FaCC(Functions as Child Components)

React children 还可以是 Function 类型,如果直接调用它会什么写法? 比如封装一个 Loading 组件,会给 children 提供 loading 参数,业务组件再根据 loading 判断需要 render 什么内容。

class LoadArea extends Component {
  state = {
    loading: true,
  };

  componentDidMount() {
    asyncFunc()
        .then(() => {
            this.setState({
              loading: false,
            })
        })
        .catch(() => {
            this.setState({
              loading: false,
            })
        })
  }

  render() {
    return (
      <React.Fragment>
        {this.props.children({
          ...this.props,
          ...this.state,
        })}
      </React.Fragment>
    );
  }
}

用法

render() {
    <LoadingArea>
        ({ loading }) => {
            loading
                ? <Wating />
                : <Main />
        }
    </LoadingArea>
}

同样的,最终执行时都是 JS,没有什么好奇怪的。

React 16.* 新版本的 Conext.Consumer 就是采用了这种写法。

render() {
    <ThemeContext.Provider value={this.state.theme}>
      ...
        <ThemeContext.Consumer>
          {({theme}) => (
            <button
              style={{backgroundColor: theme.background}}>
              Toggle Theme
            </button>
          )}
        </ThemeContext.Consumer>
      ...
    </ThemeContext.Provider>    
}

再以最近开发的例子,分享组件拆分的好处。

需求:开发倒计时组件,运营配置倒计时结束时间,倒计时初始化时间从服务端获取,结束之前显示倒计时,倒计时结束之后做对应的操作,比如切换倒计时为其他组件。

组件拆分:

  • 一个业务层容器组件,负责统筹,处理业务逻辑。(统筹规划,倒计时完要干什么,你直接跟我说)
  • 一个通用‘倒计时’的组件,向服务端轮询系统时间,计算当前剩余时间,FaCC 的形式提供给 children。(我数我的羊,你们爱干嘛干嘛)
  • 一个倒计时UI组件,对剩余时间格式化以及 UI 展示。(剩下多少,时间怎么来的,与我无关,给我什么我展示什么)

伪代码:

// CountDownContainer.js
render() {
    const {
      endTime,
      renderSomethingAfterCountDown,
    } = this.props;

    return (
      <TimeLeftProvider endTime={endTime} >
        {seconds => (
          seconds > 0
            ? <CountDown {...this.props} remainingSeconds={seconds} />
            : renderSomethingAfterCountDown()
        )}
      </TimeLeftProvider>
    );
}
// TimeLeftProvider.js
export default class TimeLeftProvider extends PureComponent {
  static propTypes = {
    children: PropTypes.func,
    endTime: PropTypes.number,
  }

  // ...

  componentDidMount() {
    this.poll();
  }

  poll() {
    queryServerTime();
    this.pollTimer = setInterval(() => {
      queryServerTime();
    }, pollInterval * 1000);
  }

  countDown() {
    setInterval(() => {
      this.setState(prevState => ({
        remainingSeconds: prevState.remainingSeconds - 1,
      }));
    }, 1000);
  }

  render() {
    const { remainingSeconds, reliable } = this.state;
    return this.props.children(remainingSeconds, reliable);
  }
}
// CountDown.js

function CountDown(props) {
    const {
      remainingSeconds,
    } = props;
    const numbers = formatSeconds(remainingSeconds);
    const inputs = ['days', 'hours', 'minutes', 'seconds'];

    return (
      <div styleName={cls}>
        {
          inputs.map(key => ({
            label: key,
            number: numbers[key],
          })).map(
             //...
          )
        }
      </div>
    );
}

最终得到的结果是:

Count Down

与此同时

  • 代码结构清晰,组件之间各司其职。
  • 组件可复用性强。
  • 单元测试简单,每个组件都只测试自身的逻辑。

推荐阅读