ReactJS组件中的常量放置

Can*_*yer 7 reactjs

从Java背景来看,在我看来,下面的常量应该在类中定义为实例变量.但是,这不起作用,如果我想从不同的函数访问变量,则必须在组件类之外定义常量.有人可以向我解释这个推理吗?我只是缺少一些简单的东西吗?我从codeacademy.com获得了这段代码.

import React from 'react';
import ReactDOM from 'react-dom';

const redPanda = {
  src: 'https://upload.wikimedia.org/wikipedia/commons/b/b2/Endangered_Red_Panda.jpg',
  alt: 'Red Panda',
  width:  '200px'
};

class RedPanda extends React.Component {
  render() {
    return (
      <div>
        <h1>Cute Red Panda</h1>
    <img 
      src={redPanda.src}
      alt={redPanda.alt}
      width={redPanda.width} />
  </div>
);
 }
}

ReactDOM.render(
  <RedPanda />,
  document.getElementById('app')
);
Run Code Online (Sandbox Code Playgroud)

May*_*kla 12

当您想要定义一些常量值(如样式或图像URL)时,最好在组件外定义它,它将成为全局值,并在该文件的每个函数/类中可用.

定义常量的另一个选择是在类实例本身,但是那个变量只能在类中使用,这意味着如果你在同一个文件中定义了两个类,那么一个类变量在另一个类中是不可用的.

像这样:

class ABC extends React.Component{
   constructor(){
      super();
      this.a = 10;
      this.b = 20;
   }

   render(){ 
      console.log(this.a, this.b);
      return (....);
   }
}
Run Code Online (Sandbox Code Playgroud)

注意: React类没有类级属性的特性,我们只能定义方法.但是如果要定义值,则需要使用类转换属性


Zah*_*mon 7

为共享常量变量/对象创建一个 constants.js 并从那里导出它以获得更好的可维护性。

export const redPanda = {
  src: 'https://upload.wikimedia.org/wikipedia/commons/b/b2/Endangered_Red_Panda.jpg',
  alt: 'Red Panda',
  width: '200px',
};

import React from 'react';
import ReactDOM from 'react-dom';
import { redPanda } from 'path/to/your/constants/file'; //import from your constants.js

class RedPanda extends React.Component {
  render() {
    return (
      <div>
        <h1>Cute Red Panda</h1>
        <img src={redPanda.src} alt={redPanda.alt} width={redPanda.width} />
      </div>
    );
  }
}

ReactDOM.render(<RedPanda />, document.getElementById('app'));
Run Code Online (Sandbox Code Playgroud)