Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
lgwebdream opened this issue Jul 6, 2020 · 2 comments
Labels
React teach_tag

Comments

@lgwebdream
Copy link
Owner

No description provided.

@lgwebdream lgwebdream added the React teach_tag label Jul 6, 2020
@lgwebdream
Copy link
Owner Author

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

@LoveWei0
Copy link

一 高阶组件

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

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

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>
  )
}
  • 这三者都能用来进行逻辑复用,区别在于高阶组件为接收组件,对其进行包装
  • render props为在render中渲染共享数据
  • hooks是以函数调用的形式共享数据.

为什么迭代 ?

  • 重名问题
  • 嵌套问题
  • 无法在return之外访问数据的问题
  • 数据来源不清晰

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
React teach_tag
Projects
None yet
Development

No branches or pull requests

2 participants