我創造了這個類如何設置初始狀態使用ES6類反應
class App extends Component{
render() {
return (
<div className="app"></div>
);
}
}
如何設置初始狀態? getInitialState()不起作用? 我做錯了什麼?反應文件也沒有幫助。
我創造了這個類如何設置初始狀態使用ES6類反應
class App extends Component{
render() {
return (
<div className="app"></div>
);
}
}
如何設置初始狀態? getInitialState()不起作用? 我做錯了什麼?反應文件也沒有幫助。
import React, { Component } from 'react';
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
text: 'Hello World'
};
}
render() {
return (
<div>
{this.state.text}
</div>
);
}
}
您可能也想看看這個職位約之間時使用一個構造函數以及何時使用getInitialState的差異。
What is the difference between using constructor vs getInitialState in React/React Native?
作爲@大衛 - 克里斯托弗 - 薩莉說,還有詹娜的偉大答案,不使用constructor
或this
的快捷方式:
class App extends Component {
state = {
text: 'Hello World'
};
render() {
return (
<div>
{this.state.text}
</div>
);
}
}
一個簡單的例子表明,輸出是在這兩種情況下是相同的:
但是,如果我們擴展父類中,transpiled輸出也有所不同,因爲參數的構造函數的數量是未知的。
根據[AST Explorer](https://astexplorer.net/#/gist/9a82ca465ae47f4273c65ad3fb87fd27/59607892ef56715fd0c75f3d45f094a676a9a3ff),這被稱爲一個ClassProperty。 – joeytwiddle
check react doc [如何在es-6類組件中設置初始狀態](https://reactjs.org/docs/react-component.html#constructor) –
另請參閱:https://stackoverflow.com/ q/37782403/1531971這看起來像是重複的。 – jdv
[在構造函數或componentWillMount中設置初始反應組件狀態?]的可能重複(https://stackoverflow.com/questions/37782403/set-initial-react-component-state-in-constructor-or-componentwillmount) –