小编典典

反应,使用扩展类创建组件和简单const =函数之间的差异

reactjs

在反应教程中:

https://egghead.io/lessons/javascript-redux-react-todo-list-example-
filtering-todos

有主要组件创建与扩展:

class TodoApp extends Component {
  render() {
    const visibleTodos = getVisibleTodos(
      this.props.todos,
      this.props.visibilityFilter
    );
    .
    . // Input and Button stuff
    .

而另一个组件就像一个包含函数的const一样创建:

const FilterLink = ({
  filter,
  children
}) => {
  return (
    <a href='#'
       onClick={e => {
         e.preventDefault();
         store.dispatch({
           type: 'SET_VISIBILITY_FILTER',
           filter
         });
       }}
    >
      {children}
    </a>
  )
}

我看到的区别是,首先使用class创建的函数使用了render函数,另一个则使用return函数将模板发回。

有什么区别?我听说将来只有扩展Component才允许使用组件?


阅读 190

收藏
2020-07-22

共1个答案

小编典典

简短的答案是,您想尽可能多地使用无状态功能组件(SFC)。您的大多数组件应该是SFC。

在以下情况下使用传统Component类:

  • 您需要本地状态(this.setState
  • 你需要一个生命周期挂钩(componentWillMountcomponentDidUpdate,等)
  • 您需要通过ref访问后备实例(例如<div ref={elem => this.elem = elem}>
2020-07-22