lgwebdream / FE-Interview

🔥🔥🔥 前端面试,独有前端面试题详解,前端面试刷题必备,1000+前端面试真题,Html、Css、JavaScript、Vue、React、Node、TypeScript、Webpack、算法、网络与安全、浏览器
https://lgwebdream.github.io/FE-Interview/
Other
6.83k stars 896 forks source link

React 高阶组件 renderprops hooks 有什么区别,为什么要不断迭代 #224

Open lgwebdream opened 4 years ago

lgwebdream commented 4 years ago

扫描下方二维码,获取答案以及详细解析,同时可解锁800+道前端面试题。

LoveWei0 commented 1 year ago

一 高阶组件

接收一个组件作为参数,返回一个组件的函数


import React from 'react'

export default function withSubscription (WrapperdComponent, selectData) { return class extends React.Component { consturctor (props) { super(props) this.state = { data: selectData(DataSource, props) } } render () { return <WrapperdComponent data={this.state.data} {...this.props} /> } } }

## 二 render props
> render props是一种在react组件之间使用一个值为函数的prop共享代码技术,具体来说就是:Render prop是一个告知组件,需要渲染什么内容的函数prop
```jsx
import React, { Component } from 'react'

export default class DataProvider extends Component {
  state = {
    name: 'Alice'
  }
  render () {
    return (
      <div>
        <p>共享数据组件自己的内部render</p>
        {this.props.render(this.state)}
      </div>
    )
  }
}
<DataProvider render={data => (<p>共享的render{data.name}</p>)} />

三 hooks

import React from 'react'

export default function useSubscription () {
  const data = DataSource.getComments()
  return [data]
}

function CommentList (props) {
  const { data } = props
  const [subData] = useSubscription()
  return (
    <div>
      this is data :{data}
      this is subData:{subData}
    </div>
  )
}