我有一个将文本映射到字母的函数:
sizeToLetterMap: function() {
return {
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'
};
}
Run Code Online (Sandbox Code Playgroud)
这些字母用于创建flickr照片网址.因此,photoUrl函数接受图像对象和大小文本对象,并调用sizeToLetterMap来为该大小文本提供字母.
功能:
photoUrl(image, size_text): function () {
var size = this.sizeToLetterMap(size_text);
}
Run Code Online (Sandbox Code Playgroud)
我不认为将sizeToLetterMap作为函数进行适当的设计.我认为它更适合作为常数.如何在ReactJS中定义常量?
Ed *_*lot 31
如果要将常量保留在React组件中,请使用statics
property,如下例所示.否则,请使用@Jim给出的答案
var MyComponent = React.createClass({
statics: {
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'
},
someOtherStatic: 100
},
photoUrl: function (image, size_text) {
var size = MyComponent.sizeToLetterMap[size_text];
}
Run Code Online (Sandbox Code Playgroud)
Roh*_*wiz 30
除了简单的React和ES6之外,您不需要使用任何东西来实现您想要的效果.根据Jim的回答,只需在正确的位置定义常量.我喜欢在外部不需要的情况下保持组件的常量局部的想法.以下是可能的用法示例.
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 (<span>
Image: {image}, Size Letter: {sizeToLetterMap[size_text]}
</span>);
}
render() {
return (
<div className="photo-wrapper">
The url is: {this.photoUrl(this.props.image, this.props.size_text)}
</div>
)
}
}
export default PhotoComponent;
// Call this with <PhotoComponent image="abc.png" size_text="thumbnail" />
// Of course the component must first be imported where used, example:
// import PhotoComponent from "./photo_component.jsx";
Run Code Online (Sandbox Code Playgroud)
好吧,有很多方法可以像javascript一样在javascript中执行此操作.我认为没有办法做出反应.这是我要做的:
在js文件中:
module.exports = {
small_square: 's',
large_square: 'q'
}
Run Code Online (Sandbox Code Playgroud)
在你的反应文件中:
'use strict';
var Constant = require('constants');
....
var something = Constant.small_square;
Run Code Online (Sandbox Code Playgroud)
你需要考虑的事情,希望这会有所帮助
警告:这是一项实验性功能,可能会在未来版本中发生巨大变化甚至不复存在
您可以使用 ES7 静态:
npm install babel-preset-stage-0
Run Code Online (Sandbox Code Playgroud)
然后添加"stage-0"
到 .babelrc 预设:
{
"presets": ["es2015", "react", "stage-0"]
}
Run Code Online (Sandbox Code Playgroud)
之后,你去
class Component extends React.Component {
static foo = 'bar';
static baz = {a: 1, b: 2}
}
Run Code Online (Sandbox Code Playgroud)
然后你像这样使用它们:
Component.foo
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
72723 次 |
最近记录: |