react 学习笔记(二):react 组件创建与传值

mac2026-08-09  4

react 中,创建组件有两种方式,函数组件和class组件

函数组件

函数组件通过编写JavaScript函数创建,创建组件中较为简单的方法,以创建一个 Hello 组件为例

function Hello(){ return (<h1>Hello World</h1>) }

函数名就是组件的名称,return的内容就是需要渲染的内容,使用的JSX语法。

 

class组件

class组件通过es6的class创建,同样以创建一个Hello组件为例

class Hello extends React.Component{ render(){ return(<h1>Hello World</h1>) } }

通过class创建的组件需要继承 React.Component,渲染的内容在 render 方法内,同样使用JSX。

 

通过props传值

“当 React 元素为用户自定义组件时,它会将 JSX 所接收的属性(attributes)转换为单个对象传递给组件,这个对象被称之为 ‘props’”

在函数组件中,props作为第一个参数传入

function Hello(props){ return (<h1>{props.msg}</h1>) } ReactDOM.render(<Hello msg="Hello World"/>, document.getElementById('root'));

在 class 组件中,在构造函数中处理传入的 props,调用时使用 this.props

class Hello extends React.Component{ constructor(props) { super(props); } render(){ return(<h1>{this.props.msg}</h1>) } }

两种组件的区别

函数组件是无状态组件,没有 state,也有生命周期。而 class 组件实现了对生命周期以及 state 的管理。

最新回复(0)