簡體   English   中英

如何在 create-react-app 中添加構造函數?

[英]How do I add Constructor in create-react-app?

我剛剛開始使用 create-react-app,對 src 設置不是很熟悉。 我注意到在 App.js 中,導出的 App 組件是一個函數,而不是類 App extends React.Component...

我似乎無法向它添加構造函數。 有誰知道我在哪里可以這樣做? 謝謝

您可以將函數更改為類:


import ReactDOM from 'react-dom';
import React, { Component } from 'react';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      text: 'App.js'
    }
  }

  render() {
    return (
      <div>
          {this.state.text}
      </div>
    )
  }
}

export default App

只需在函數內使用useEffect

喜歡:

React.useEffect(() => {
    // Whatever you like
    console.log("Called in starting of function");
  }, []);

CRA 團隊將設置更新為新的 React 鈎子。 你在談論舊的反應設置。 你可以轉換它

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (

class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  render() {

但我會建議你學習 react hooks 來保持你的技能更新。

由於 App 是一個功能組件,它沒有組件生命周期。 因此,您不能指定構造函數。

但是對於基於類的組件,您可以使用構造函數

class App extends React.Component {
 constructor(props) {
    super(props);

 }

 render(){
 return(
 // code
 //code
 )}
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM