Javascript React组件此变量不呈现
我有这个react组件,我创建了一个常量,如下所示:Javascript React组件此变量不呈现,javascript,reactjs,Javascript,Reactjs,我有这个react组件,我创建了一个常量,如下所示: export class MyComponent extends React.Component { constructor() { super(); const mytext = 'Some Text'; } render() { return ( <div> {this.mytext} </div> ); } } 导出类
export class MyComponent extends React.Component {
constructor() {
super();
const mytext = 'Some Text';
}
render() {
return (
<div>
{this.mytext}
</div>
);
}
}
导出类MyComponent扩展了React.Component{
构造函数(){
超级();
const mytext='一些文本';
}
render(){
返回(
{this.mytext}
);
}
}
当我使用{This.mytext}时,此常量没有呈现mytext
我做错了什么?
{this.mytext}
应该是{mytext}
如果您想要声明一个类型为const的全局变量,那么您需要这样定义它
const mytext = 'Some Text';
export class MyComponent extends React.Component {
constructor() {
super();
}
render() {
return (
<div>
{mytext}
</div>
);
}
const this.mytext='Some Text'代码>和{mytext}
。。。。。。!mytext的数据类型为const。所以你需要把它{this.mytext}改为{mytext}@Jai我想const this.mytext='Some Text';语法错误。@Ved这正是这些挂起点+感叹号的意思meant@Sebas我不明白你的意思。请解释。所以我不能在组件内定义变量?不。你可以这样定义。mytext,但不能const mytext。
export class MyComponent extends React.Component {
constructor() {
super();
this.mytext = "VED"//you can use it now anywhere inside your file
}