定义:在调用组件时,引入一个函数类型的 prop,这个 prop定义了组件的渲染方式。
典型应用:react-router
<Route path={url}
render={(props) => {
return <MyComponent {...this.props} />
}}/>
1、定义
class RenderComponent extends React.Component {
constructor (props) {
super(props)
this.state = {
message: '我是提取出的公用状态'
}
}
componentWillMount () {}
componentDidMount () {}
componentDidUpdate (prevProps, prevState, snapshot) {}
render () {
const {renderMe,age} = this.props
const {message} = this.state
return <div>
<div>年龄:{age}</div>
<div>{message}</div>
{renderMe(message)}
</div>
}
}
2、实例1
class Cat extends React.Component {
render () {
return <div>
<RenderComponent {...this.props}
renderMe={(message) => {
return <div>
<div>我是cat组件,显示的内容,我自己空值需要显示的内容</div>
<div>公用状态:{message + 1}</div>
</div>
}}/>
</div>
}
}
3、实例2
class Dog extends React.Component {
render () {
return <div>
<RenderComponent {...this.props}
renderMe={(message) => {
return <div>
<div>Dog组件</div>
<div>{message}</div>
</div>
}}/>
</div>
}
}
使用
<Dog age={9} />
<Cat age={120} />
注意:当render props 的名称是children时,可提供2种写法
class Dog extends React.Component {
render () {
return <div>
<RenderComponent {...this.props}
children={(message) => {
return <div>
<div>Dog组件</div>
<div>{message}</div>
</div>
}}/>
</div>
}
}
class Dog extends React.Component {
render () {
return <div>
<RenderComponent {...this.props}>
{(message) => {
return <div>
<div>Dog组件</div>
<div>{message}</div>
</div>
}}
</RenderComponent>
</div>
}
}