我不確定何時將響應組件聲明爲簡單的獨立函數,而不是常規的class myComponent extends Component
語法。使用來自陣營的文檔的例子(位於here):何時應該將一個反應組件聲明爲一個函數,而不是一個類?
被稱爲一個「組件」
function BoilingVerdict(props) {
if (props.celsius >= 100) {
return <p>The water would boil.</p>;
}
return <p>The water would not boil.</p>;
}
以下雖然這似乎僅僅是一個函數,而且被聲明像任何普通的舊功能。然後,在接下來的一段,以下也被定義爲一個組成部分,看起來更像方式,我認爲一個組件應該看看:
class Calculator extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.state = {temperature: ''};
}
handleChange(e) {
this.setState({temperature: e.target.value});
}
render() {
const temperature = this.state.temperature;
return (
<fieldset>
<legend>Enter temperature in Celsius:</legend>
<input
value={temperature}
onChange={this.handleChange} />
<BoilingVerdict
celsius={parseFloat(temperature)} />
</fieldset>
);
}
}
是什麼這兩個「組件」之間的區別?如果第一個示例沒有從Component類繼承並且沒有使用React.createClass
創建,那麼它實際上是一個組件?我希望有人解釋這種區別,因爲我無法在文檔的任何地方找到答案。
的區別似乎很清楚;一個有狀態,一個沒有。 React文檔聲明,功能(「功能」)組件既沒有狀態也沒有生命週期事件(至少包括用戶代碼)。 –