Open lgwebdream opened 4 years 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>)} />
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>
)
}
扫描下方二维码,获取答案以及详细解析,同时可解锁800+道前端面试题。