什么是函数组件
- props 传递数据
- props 传递函数
- 以属性方式传递数据和函数
- props 类型检查
- 函数组件无法代替 class组件
import React from 'react'import PropTypes from 'prop-types'// 对 Component的props属性进行类型检查Parent.propTypes = { onChange: PropTypes.func.isRequired, // 数组对象 value: PropTypes.arrayOf(PropTypes.object).isRequired}function Parent(props) { const {value, onChange} = props return ( <div> Parent </div> )}export default Parent
函数组件的特点
- 纯函数,输入 props,输出 jsx
- 没有 this,没有实例,没有生命周期函数,没有 state
- memo优化,类似 PureComponent
- useEffect优化生命周期
class组件
class List extends React.Component { constructor(props) { super(props) } render() { const {data} = this.props return ( <ul> <ListItem {...props}/> </ul> ) }}function ListItem({data}) { return data.map(row => <li key={row.id}>{row.title}</li>)}
function组件
function List(props) { return ( <ul> <ListItem {...props}/> </ul> )}export default Listfunction ListItem({data}) { return data.map(row => <li key={row.id}>{row.title}</li>)}
TableList函数组件
import React from 'react'import PropTypes from 'prop-types'import { Table, Popconfirm, Button } from 'antd'TodoList.propTypes = { onDelete: PropTypes.func.isRequired, tbody: PropTypes.array.isRequired,}function TodoList(props) { const { onDelete, tbody } = props const renderAction = (text, record) => { return ( <Popconfirm title="Delete?" onConfirm={() => onDelete(record.id)}> <Button>删除</Button> </Popconfirm> ) } const columns = [ { title: 'Name', dataIndex: 'name', }, { title: 'Actions', dataIndex: 'action', render: (text, record) => renderAction, } ] return ( <Table rowKey={ record => record.id } dataSource={ tbody } columns={ columns } /> )}export default TodoList