12月 09, 2019 React
### React 中的 Reference

Reference 是在 React 中很常會使用到的一種方法,用處是可以把引入的 HTML DOM 物件回傳出來。使用時我們會用以下的語法 :

```js

class DemoComponent extends React.Component {

	constrcutor(props) {
		// create reference object
		this.divRef = React.createRef();

		// init state
		this.state = {];
	}

	componentDidMount() {
		// print <div> in console
		console.log(this.divRef.current);
	}

	render() {
		return (<div ref={ this.divRef }>hello world</div>);
	}
}
```

當 Render 事件完成後,DOM 的物件便可以通過我們建立的 Reference 取得。然後你可以直接對物件進行 DOM 的操作。

### 只有 DOM 物件才能加入 ref

要注意的是,只有 DOM 物件才可以進行 `ref` 的操作,對於非 DOM 物件加入 `ref` 會有機會產生錯誤。

```js
// parent object render function
render() {
	return (<DemoComponent ref={this.componentRef} />);
}
```

這樣是會炒車的 !

### 提取自訂物件的 DOM ref

如果想要在自訂的 React Component 取得內裏的 DOM Reference,我們可以使用以下的 Pattern 去解決 (唔知叫什麼名稱)。

```js
// add code to component did update
componentDidUpdate() {
	// assign props
	var props = this.props;

	// check has onRef event listener
	typeof props.onRef === 'function' && props.onRef(this.divRef);
}
```

然後在 parent component 使用 component 時加入 `onRef` 事件 :

```js
// on child component return ref
onDemoComponentRef(ref) {
	this.divRef = ref;
}

// parent object render function
render() {
	return (<DemoComponent onRef={ ref => this.onDemoComponentRef(ref) } />);
}
```

這樣便可以有系統地取得自訂 Component 的 Reference。
過去文章
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)