繁体   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