12月 03, 2019 React
今天講一下 React 的 Props。

在 React 中我們會常常使用到 props 來傳遞資料,把父系的資料傳送到子系的物件上。需我們在物件上收 props 通常會是以下的格式 :

```js
// 例子 1 (直接使用 function 來建立 element)
const ReactElement = props => {

	// extract props elements
	var { style, children } = this.props;
	
	// render
	return (
		<div style={ ...style }>
			{ children }
		</div>
	);
};

// 例子 2 (使用 class 的方法建立 element)
class ReactElement extends React.Component {
	constructor(props) {		
		super(props);
	}
	
	render() {

		// extract props elements
		var { style, children } = this.props;
		
		// render
		return  (
			<div style={ ...style }>
				{ children }
			</div>
		);
	}
}
```

在例子 2 的情況下,筆者最近多了一個習慣,使用在存取 props 時更能預測資料的預定值。如下:

```js
getProps(props) {
	
	// set input object
	props = props || this.props;
	
	// return props values
	return {
		
		// check and set default value for style
		style: typeof props.style === 'object'? props.style: {},

		// check and set default value for children
		children: typeof props.children === 'object' && Array.isArray(props.children)? props.children: []
	};
}
```

使用以上的方法,當你在抽取要使用 props 的資料時,便可以機乎確定所使用的資料是在你的預測範圍內,以減少發生錯誤的可能性。

```js
var { style, children } = this.getProps();
```

在可以用於 componentDidUpdate 的情況

```js
componentDidUpdate(oldProps) {
	var oP = self.getProps(oldProps);
	var cP = self.getProps();
}
```

當然如果正統來說是使用 PropType 和 defaultProps 較為好。

相關文件 : https://zh-hant.reactjs.org/docs/typechecking-with-proptypes.html 
過去文章
2025 (9)
4 (5)
3 (1)
2 (3)
2024 (25)
11 (3)
10 (3)
9 (1)
3 (18)
2022 (6)
10 (1)
6 (2)
5 (1)
3 (1)
1 (1)
2021 (21)
11 (7)
7 (1)
6 (2)
5 (2)
4 (6)
3 (2)
2 (1)
2020 (92)
12 (1)
11 (2)
10 (4)
9 (10)
8 (5)
7 (1)
6 (3)
5 (1)
4 (4)
3 (25)
2 (7)
1 (29)
2019 (57)
12 (25)
11 (7)
9 (25)