有两种可行的方法来创建一个组件:
-
Function Components: 这是创建组件最简单的方式。这些是纯 JavaScript 函数,接受 props 对象作为第一个参数并返回 React 元素:
function Greeting({ message }) {
return <h1>{`Hello, ${message}`}</h1>
}
-
Class Components: 你还可以使用 ES6 类来定义组件。上面的函数组件若使用 ES6 的类可改写为:
class Greeting extends React.Component {
render() {
return <h1>{`Hello, ${this.props.message}`}</h1>
}
}
通过以上任意方式创建的组件,可以这样使用:
<Greeting message="semlinker"/>
在 React 内部对函数组件和类组件的处理方式是不一样的,如:
// 如果 Greeting 是一个函数
const result = Greeting(props); // <p>Hello</p>
// 如果 Greeting 是一个类
const instance = new Greeting(props); // Greeting {}
const result = instance.render(); // <p>Hello</p>