首页 文章

将React组件从函数重构为ES6类

提问于
浏览
5

我是ES6的新手 . 在编写React组件的不同方法上有点困惑 . 我从“React.createClass”开始,然后使用ES6类语法移动到“扩展React.Component” .

现在关注Redux教程,我看到他们以这种方式定义组件

import React, { PropTypes } from 'react'

const Todo = ({ onClick, completed, text }) => (
    <li onClick={onClick} style={{ textDecoration: completed ? 'line-through' : 'none' }} >
        {text}
    </li>
)

Todo.propTypes = {
    onClick: PropTypes.func.isRequired,
    completed: PropTypes.bool.isRequired,
    text: PropTypes.string.isRequired
}

export default Todo

我怎样才能重构这个“函数”移动到扩展React.component的ES6类?我想返回JSX是render()方法,不是吗?那么onClick,已完成的文本参数呢?

谢谢

2 回答

  • 3

    对于你的组件实际上最好使它成为纯函数,而不是ES6类,因为它可以呈现为它的函数 props 并且不维护状态 . 您仍然可以使用ES6语法(导出,箭头功能等) .

    Facebook's explanation:"In an ideal world, most of your components would be stateless functions because in the future we’ll also be able to make performance optimizations specific to these components by avoiding unnecessary checks and memory allocations. This is the recommended pattern, when possible."

    import { PropTypes } from 'react'
    
    function Todo = (props) => (
        <li onClick={props.onClick} style={{ textDecoration: props.completed ? 'line-through' : 'none' }} >
            {props.text}
        </li>
    )
    
    Todo.propTypes = {
        onClick: PropTypes.func.isRequired,
        completed: PropTypes.bool.isRequired,
        text: PropTypes.string.isRequired
    }
    
    export default Todo
    
  • 4

    ES6语法等效于:

    import React, { Component, PropTypes } from 'react'
    
    class Todo extends Component {
      render() {
        const { onClick, completed, text } = this.props
    
        return (
          <li onClick={onClick} style={{ textDecoration: completed ? 'line-through' : 'none' }} >
              {text}
          </li>
        )
      }
    }
    Todo.propTypes = {
      onClick: PropTypes.func.isRequired,
      completed: PropTypes.bool.isRequired,
      text: PropTypes.string.isRequired
    }
    
    export default Todo
    

    如果您使用 babel 来转换代码并且您拥有class properties transform,那么您可以执行以下操作:

    import React, { Component, PropTypes } from 'react'
    
    class Todo extends Component {
      static propTypes = {
        onClick: PropTypes.func.isRequired,
        completed: PropTypes.bool.isRequired,
        text: PropTypes.string.isRequired
      }
    
      render() {
        const { onClick, completed, text } = this.props
    
        return (
          <li onClick={onClick} style={{ textDecoration: completed ? 'line-through' : 'none' }} >
              {text}
          </li>
        )
      }
    }
    
    export default Todo
    

    为了清楚这个第二个例子不能被认为是“标准ES6”,但我发现静态属性更加清晰,所以我认为值得展示这种方法 .

相关问题