【问题标题】:React method return value won't show in render()React 方法返回值不会在 render() 中显示
【发布时间】:2021-06-12 10:08:24
【问题描述】:

我在 React 中玩耍,我试图让一个方法返回一个值,然后我将使用它在 render() 方法中显示,但是当我尝试什么都不显示时。

import React, { Component } from "react";

class Test extends Component {
  constructor(props) {
    super(props);
    this.DisplayTest = this.DisplayTest.bind(this);
  }
  DisplayTest() {
    return <h1>Test</h1>;
  }
  render() {
    return <div>{this.DisplayTest}</div>;
  }
}
export default Test;

【问题讨论】:

  • 您需要将方法调用为{this.DisplayTest()}

标签: javascript html node.js reactjs


【解决方案1】:

DisplayTest 是一种方法,因此为了返回一个值,您必须执行它。

  render() {
    return <div>{this.DisplayTest()}</div>;
  }

另一种方法是使用类getter

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get

所以,你必须声明一个 getter 方法,比如

 get DisplayTest() {
    return <h1>Test</h1>;
  }

  render() {
    return <div>{this.DisplayTest}</div>;
  }

然后,您当前的实现将起作用。

【讨论】:

    【解决方案2】:

    请添加以下 { this.DisplayTest() }

    【讨论】:

      猜你喜欢
      • 2023-03-28
      • 1970-01-01
      • 2018-04-25
      • 2015-01-02
      • 2023-04-05
      • 2019-11-26
      • 2021-04-03
      • 2019-08-11
      • 1970-01-01
      相关资源
      最近更新 更多