今天講一下 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