【问题标题】:React. In class component Return doesnt work做出反应。在类组件中返回不起作用
【发布时间】:2020-10-23 11:29:29
【问题描述】:

我是 react 新手。今天才开始。当我写返回时,我在类组件主题上,它应该返回 htm,但它没有。有人知道我的错误吗?

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {
  render() {
    return (
      
    )
  }
}

export default App;

我要发图

【问题讨论】:

  • 代码sn-p和右图不完整。你还没有写出你想要它返回的东西。你问的是这个吗?
  • 您需要在return 语句中添加一些代码。

标签: reactjs class components


【解决方案1】:

只需在第 8 行添加 <div>Hello</div>(或任何您想出现的内容)

【讨论】:

    【解决方案2】:
    import React, { Component } from 'react';
    import logo from './logo.svg';
    import './App.css';
    
    class App extends Component {
      render() {
        return (
          
        )
      }
    }
    
    export default App;
    

    是基于类的组件样板的一个很好的例子。但是,您是说返回……嗯……什么都没有。无需深入了解 JSX、Babel 等的复杂性,基本答案是您的课程没有返回任何内容,因此没有什么可显示的。

    class App extends Component {
      render() {
        return (
          <div>
            <h1>Oh, hi there!</h1>
          </div>
        )
      }
    }
    

    将导致 DOM 呈现一个 div 和一个带有文本“Oh, hi there!”的 h1。

    这本质上与编写标准函数并返回一个值相同,但您返回的是 JSX! 如果您正在编写具有相同问题的标准 JS 函数,则示例如下:

    const sumNumbers = (firstNumber, secondNumber) => { 
      let answer = firstNumber + secondNumber
      return;
    }
    
    console.log(sumNumbers(1, 2));
    // undefined
    

    对比

    const sumNumbers = (firstNumber, secondNumber) => { 
      return firstNumber + secondNumber;
    }
    
    console.log(sumNumbers(1, 2));
    // 3
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-24
      • 2021-02-02
      • 2021-06-27
      • 2018-08-31
      • 1970-01-01
      • 2017-10-25
      相关资源
      最近更新 更多