-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathSpread props trap in JSX.md
51 lines (41 loc) · 1.17 KB
/
Spread props trap in JSX.md
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# Spread props trap in JSX
```jsx
// A normal Text Component
import React from 'react';
export default function Text(props) {
const { text, ...restProps } = props;
// You have no idea what to expect in restProps as it's passed down from parent
return <div style={{ color: 'red'}} {...restProps}> { text } </div>
}
```
```jsx
import React, { Fragment } from 'react';
import ReactDOM from 'react-dom';
export default function withHighlight(Comp) {
return (props) => {
return <Comp style={{ fontSize: 20 }} {...props} />
}
}
// what's the color ? style overwritten
const Comp = withHighlight(Text);
ReactDom.render(
<Fragment>
<Text text='abc'/>
<Comp text='abc'/>
</Fragment>,
document.getElementById('root')
)
```
> Solution: merge props if necessary
```jsx
// A normal Text Component
import React from 'react';
export default function Text(props) {
const { text, style, ...restProps } = props;
return <div style={{ color: 'red', ...(style == null ? {} : style)}} {...restProps}>
{ text }
</div>
}
```
## Notice
* If you want to follow the latest news/articles for the series of my blogs, Please [「Watch」](https://github.com/n0ruSh/blogs/)to Subscribe.