反应,使用扩展类创建组件和简单 const = 函数之间的差异 [英] react, differences between component create with extend class and simple const = function

查看:40
本文介绍了反应,使用扩展类创建组件和简单 const = 函数之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在反应教程中:

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

使用扩展创建主要组件:

class TodoApp extends Component {使成为() {const visibleTodos = getVisibleTodos(this.props.todos,this.props.visibilityFilter);..//输入和按钮的东西.

和另一个组件就像一个包含函数的常量一样创建:

const FilterLink = ({筛选,孩子们}) =>{返回 (<a href='#'onClick={e =>{e.preventDefault();store.dispatch({类型:'SET_VISIBILITY_FILTER',筛选});}}>{孩子们}</a>)}

我看到的不同之处,首先使用类创建使用渲染函数,另一个使用返回函数发送回模板.

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

解决方案

参见:React.createClass 与 ES6 箭头函数

简短的回答是,您希望尽可能多地使用无状态功能组件 (SFC);您的大部分组件应该是 SFC 的.

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

  • 您需要本地状态 (this.setState)
  • 您需要一个生命周期钩子(componentWillMountcomponentDidUpdate 等)
  • 您需要通过 refs 访问支持实例(例如

    this.elem = elem}>)

In react tutorial:

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

there is main component create with extends:

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

and another components just create like a const that hold a function:

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

the difference i see, first created with class use a render function, and the another a return function to send back the template.

What are the differences? I've heard components in the future only will be allowed with extend Component ?

解决方案

See: React.createClass vs. ES6 arrow function

The short answer is that you want to use Stateless Functional Components (SFC) as often as you can; the majority of your components should be SFC's.

Use the traditional Component class when:

  • You need local state (this.setState)
  • You need a lifecycle hook (componentWillMount, componentDidUpdate, etc)
  • You need to access backing instances via refs (eg. <div ref={elem => this.elem = elem}>)

这篇关于反应,使用扩展类创建组件和简单 const = 函数之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆