React官方文档也一直没看完,sigh
Accessibility
-
Render Props
What is render prop
a technique for sharing code between React components using a prop whose value is a function
A component with a render prop takes a function that returns a React element and calls it instead of implementing its own render logic:
1
<DataProvider render={data => (<h1>Hello {data.target}</h1>)}
Why render prop?
in react, state of components does not share automatically
to make components reusable, sometimes, we have to pass the state of component A to component B, without embedding it in the component A, in order to use A’s state
1
2
3
4
5
6
7
8class Cat extends React.Component {
render() {
const mouse = this.props.mouse
return (
<img src='/cat.jpg' style={{ position: 'absolute', left: mouse.x, top: mouse.y }}
)
}
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35class Mouse extends React.Component {
constructor(props) {
super(props)
this.handleMouseMove = this.handleMouseMove.bind(this)
this.state = { x: 0, y: 0 }
}
handleMouseMove(event) {
this.setState({
x: event.clientX,
y: event.clientY,
})
}
render() {
return (
<div style={{ height: '100%' }} onMouseMove={this.handleMouseMove}>
{this.props.render(this.state)}
</div>
)
}
}
class MouseTracker extends React.Component {
render() {
return (
<div>
<h1>Move the mouse around!</h1>
<Mouse render={mouse => (
<Cat mouse={mouse} />
)}/>
</div>
)
}
}a render prop is a function prop that a component uses to know what to render
Using tips
- any prop that is a function that a component uses to know what to render is technically a “render prop”, it does not necessarily need to be a prop named render