gpt4 book ai didi

javascript - React 组件 this.variable 不渲染

转载 作者:行者123 更新时间:2023-12-03 04:32:03 25 4
gpt4 key购买 nike

我有这个 React 组件,并且创建了一个 const,如下所示:

export class MyComponent extends React.Component {
constructor() {
super();
const mytext = 'Some Text';
}

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

);
}
}

当我使用 {this.mytext} 时,此常量不会呈现 mytext

我做错了什么?

最佳答案

{this.mytext} 应为 {mytext}

如果你想声明一个 const 类型的全局变量,那么你需要像这样定义它

    const mytext = 'Some Text';
export class MyComponent extends React.Component {
constructor() {
super();

}

render() {
return (
<div>
{mytext}
</div>

);
}

编辑1。声明全局变量的更好方法可以是:

export class MyComponent extends React.Component {
constructor() {
super();
this.mytext = "VED"//you can use it now anywhere inside your file
}

关于javascript - React 组件 this.variable 不渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43450647/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com