定义 ES6 React 组件的两种方式

Two ways of defining ES6 React Components

我正在查看 this fiddle 的 MobX,我也在 E​​S6 的其他地方看到了这两种定义 React 组件的方法,比如 Dan Abramov 的 egghead redux 视频系列。

@observer
class TodoListView extends Component {
    render() {
        return <div>
            <ul>
                {this.props.todoList.todos.map(todo => 
                    <TodoView todo={todo} key={todo.id} />
                )}
            </ul>
            Tasks left: {this.props.todoList.unfinishedTodoCount}
        </div>
    }
}

const TodoView = observer(({todo}) =>
    <li>
        <input
            type="checkbox"
            checked={todo.finished}
            onClick={() => todo.finished = !todo.finished}
        />
        <input
            type="text"
          value={todo.title}
          onChange={ e => todo.title = e.target.value } />
    </li>
);

我的问题是,什么时候使用每种类型合适?

似乎更简单的组件能够使用更简单的语法,但我想要遵循规则或准则。

谢谢!

第二种模式称为“无状态功能组件”,推荐在几乎所有情况下使用它。 SFC(无状态功能组件)是仅依赖于它们 props 的纯功能。它们更容易测试,彼此解耦,并且在未来将比其他模式有显着的性能提升。 (source 来自官方的 React 文档)

他们有一些陷阱,即:

  • 无法将 ref 附加到 SFC。 (src, src2)
  • 它们不能有内部状态。 (src)
  • 他们不能使用生命周期方法。 (例如 componentDidMountsrc

如果您需要这些东西中的任何一个,请首先确保没有办法绕过它们,然后才使用 ES6 classReact.createClass 模式。


我强烈推荐 Dan Abramov 的 "Should I use React.createClass, ES6 Classes or stateless functional components?" by James K Nelson to understand the tradeoffs and difference between these patterns, and "Presentational and Container Components" 来解释 Redux 应用程序最常用的结构。

React.createClass VS ES2015 类 VS 函数式无状态组件

在 React 中,有 3 种主要的创建新组件的方法。

第一个与 React 库一起引入的是 React.createClass,它具有以下语法:

var TestComponent = React.createClass({
 render: function(){
      return <p>{this.props.children}</p>;
 }
})

React.render(<TestComponent>This will be a paragraph element!</TestComponent>, document.body);

之后,在 React 0.13 版本中,我们可以直接将我们的组件定义为 ES2015 类:

class TestComponent extends React.Component {
 render () {
      return <p>{this.props.children}</p>;
 }
}

React.render(<TestComponent>This will be a paragraph element!</TestComponent>, document.body);

React 0.14 引入了创建那些称为无状态组件的功能,也称为功能组件或纯组件,因为它们被声明为没有状态的函数,并且 returns 在给定相同道具的情况下使用相同的标记:

const TestComponent = (props) => <p>props.children</p>;

ReactDOM.render(<TestComponent>This will be a paragraph element!</TestComponent>, 
document.querySelector('#root'));

这些无状态组件对于 React 来说渲染起来要轻得多,并且还具有与 React 无关的优势,这意味着它们可以在给定相同输入的情况下以任何其他方式呈现并产生相同的输出。

所以你应该在你的应用程序中使用什么取决于。各有优缺点,应在特定条件下使用。有时您不能使用无状态组件。

当您的组件需要生命周期方法或者您需要访问 'this' 以获得 props 以外的任何内容时,请使用 ES2015 (ES6) 类 或 React.createClass。