How to define constants in ReactJS

前端 未结 5 2173
无人共我
无人共我 2021-02-03 18:42

I have a function that maps text to letters:

sizeToLetterMap: function() { 
     return {
                small_square: \'s\',
                large_square: \'q\         


        
5条回答
  •  有刺的猬
    2021-02-03 19:10

    You don't need to use anything but plain React and ES6 to achieve what you want. As per Jim's answer, just define the constant in the right place. I like the idea of keeping the constant local to the component if not needed externally. The below is an example of possible usage.

    import React from "react";
    
    const sizeToLetterMap = {
      small_square: 's',
      large_square: 'q',
      thumbnail: 't',
      small_240: 'm',
      small_320: 'n',
      medium_640: 'z',
      medium_800: 'c',
      large_1024: 'b',
      large_1600: 'h',
      large_2048: 'k',
      original: 'o'
    };
    
    class PhotoComponent extends React.Component {
      constructor(args) {
        super(args);
      }
    
      photoUrl(image, size_text) {
        return (
          Image: {image}, Size Letter: {sizeToLetterMap[size_text]}
        );
      }
    
      render() {
        return (
          
    The url is: {this.photoUrl(this.props.image, this.props.size_text)}
    ) } } export default PhotoComponent; // Call this with // Of course the component must first be imported where used, example: // import PhotoComponent from "./photo_component.jsx";

提交回复
热议问题