首页 > 解决方案 > React 方法返回值不会在 render() 中显示

问题描述

我在 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;

标签: javascripthtmlnode.jsreactjs

解决方案


DisplayTest is a method therefore in order to return a value, you will have to execute it.

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

Another way is to make use of class getter

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

So, you will have to declare a getter method like

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

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

And then, your current implementation will work.


推荐阅读