易百教程

42、如何在 React 中创建组件?

在 React 中创建组件有两种可能的方式:
函数组件: 这是在 React 中创建组件的最简单方法。这些是接受 props 对象作为第一个参数并返回 React 元素的纯 JavaScript 函数:

function Greeting({ message }) {  
  return <h1>{`Hello, ${message}`}</h1>  
}

类组件: 类组件方法方便使用 ES6 类来定义组件。上面的函数组件可以写成:

class Greeting extends React.Component {  
  render() {  
    return <h1>{`Hello, ${this.props.message}`}</h1>  
  }  
}