Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

有無加上constructor的差異 #28

Closed
kuolun opened this issue Sep 27, 2016 · 4 comments
Closed

有無加上constructor的差異 #28

kuolun opened this issue Sep 27, 2016 · 4 comments

Comments

@kuolun
Copy link

kuolun commented Sep 27, 2016

hi 2個問題想請問一下
(1)
在Ch03/reactjs-introduction.md這邊有提到
ES6 Class component中render是唯一必須的方法

在Ch04/props-state-introduction.md
使用 ES6 Class Component 寫法這邊
有用到constructor

是否如果沒有用到state的話,可以不用寫constructor?

(2)
Ch04/react-component-life-cycle.md
Component 生命週期展示那段code中
this.handleClick = this.handleClick.bind(this);
可以稍微說明一下為什麼需要這行呢?
謝謝

@b12031106
Copy link
Contributor

(1)
理論上是,不過如果你沒有用到 state 的話,
那是不是就應該直接用 Functional Component 的寫法,
而不是 ES6 Class component 呢?

(2)
關鍵在 handleClick 執行的時候,this 代表什麼,
在教學的前一篇 Props、State、Refs 與表單處理 中的 js 範例裡有提到:

// 與 ES5 React.createClass({}) 不同的是 component 內自定義的方法需要自行綁定 this context,或是使用 arrow function 
this.tick = this.tick.bind(this);

官方的說明也有解釋為什麼要這樣做,可以參考看看:
https://facebook.github.io/react/docs/reusable-components.html#es6-classes

@kdchang
Copy link
Owner

kdchang commented Sep 28, 2016

@b12031106 感謝協助~:)

@kuolun 感謝您的提問

(1)
若是需要綁定 this.方法或是需要在 constructor 使用 props,定義 state,就需要 constructor。若是在其他方法(如 render)使用 this.props 則不用一定要定義 constructor。
不過如果只有需要話 render UI 的話,Functional Component 是比較好的寫法。

關於 React ES6 class constructor super() 解釋可以參考 React ES6 class constructor super()

(2)
關於 Javascript this 用法可以參考 Javascript:this用法整理

希望對你有幫助,謝謝:)

@kuolun
Copy link
Author

kuolun commented Sep 28, 2016

感謝兩位的回覆,我研究研究那些參考連結內容先
謝謝
👍

@kdchang
Copy link
Owner

kdchang commented Sep 29, 2016

@kuolun 不會~那我先 close issue 囉,有問題再 reopen ,謝謝~

@kdchang kdchang closed this as completed Sep 29, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants