javascript - 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;
解决方案
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.
推荐阅读
- python - DNS.query 与 Socket.gethostbyname
- unit-testing - 在 jest-expo 中测试反应组件总是失败
- javascript - 出现“DevTools 无法解析 SourceMap”错误
- mapbox - 在 Map box / Turf JS 中围绕一组点画一个圆圈
- css - 显示地图中除最后一个子跨度之外的所有跨度
- java - android工作室错误:org.objectweb.asm.ClassVisitor
- salesforce - Salesforce Lighting-内联编辑-显示自定义下拉更改值的文本框
- reactjs - 如何在reactjs中下载图像?
- c# - 在函数中接受一种以上类型的枚举
- react-native - 无法在空对象上获取属性“packageName”