Я превращаю компонент React.js в модуль Common.js, используя module.exports, и у меня есть проблема с доступом к этому «элементу» в контексте элемента компонента из одного из его методы.область действия «this» in module.exports
Ниже представлен весь компонент. Я разместил комментарий над строкой, где возникает проблема. Сначала я попробовал менее подробный пример, но я не думаю, что этого было достаточно, чтобы объяснить проблему.
var React = require('react');
var GSAP = require('gsap');
var Psychedelicon = React.createClass({
cycleColors: function() {
var touchPlatforms = ['iPhone', 'iPad', 'iPod', 'Android', 'Linux armv7l', 'WinCE'];
isTouch = false;
iDevice = false;
isDroid = false;
plat = navigator.platform;
if(plat === 'iPhone' || plat === 'iPad' || plat === 'iPod') {
isTouch = true;
iDevice = true;
}
else if (plat === 'Linux armv7l' || plat === 'Android') {
isTouch = true;
isDroid = true;
}
else {
for (var i = 0; i < touchPlatforms.length; i++) {
if (plat === touchPlatforms[i]) {
isTouch = true;
break;
}
else {
isTouch = false;
}
}
}
var isIE = false
if (navigator.userAgent.toLowerCase().indexOf('msie') > -1 || navigator.userAgent.toLowerCase().indexOf('trident') > -1) {
isIE = true
}
var isFF = false
if (navigator.userAgent.toLowerCase().indexOf('firefox') != -1) {
isFF = true
}
if(!isTouch) {
var ColorSwirl = function(colorSet,defaultColor,time) {
var storedResult;
var randomColor = function(theArray) {
var result = theArray[Math.floor(Math.random() * (theArray.length))];
if(result === storedResult){
return(defaultColor)
}
else {
storedResult = result;
return(result);
}
}
var theLuckyColors = {top:randomColor(colorSet),bottom:randomColor(colorSet)};
var swirl = function(){
//!!!!On this line the problem occurs onUpdateParams must reference the element accepting the execution event (onMouseEneter)
TweenLite.to(theLuckyColors, time, {colorProps:{top:randomColor(colorSet), bottom:randomColor(colorSet)}, onUpdate:colorize, onUpdateParams:[this],onComplete:swirl});
}
gradients
var colorize = function(el) {
if(isIE) {
TweenLite.set(el, {
backgroundImage:'-ms-radial-gradient(center,circle cover,' + theLuckyColors.top + ' 0%, ' + theLuckyColors.bottom + ' 100%)'
});
}
else if(isFF) {
TweenLite.set(el, {
backgroundImage:'-moz-radial-gradient(center,circle cover,' + theLuckyColors.top + ' 0%, ' + theLuckyColors.bottom + ' 100%)'
});
}
else {
TweenLite.set(el, {
backgroundImage:'radial-gradient(circle,' + theLuckyColors.top + ', ' + theLuckyColors.bottom + ')',
backgroundImage:'-webkit-radial-gradient(circle,' + theLuckyColors.top + ', ' + theLuckyColors.bottom + ')'
});
}
}
swirl();
}
ColorSwirl(['red','green','#4B0082','#9F00FF','yellow','orange'],'blue',.15);
}
},
stopTheCycle: function() {
},
render: function() {
return (
<a className="psychedelicon" href={this.props.href} target={this.props.target} onMouseEnter={this.cycleColors} onMouseLeave={this.stopTheCycle}>
<i className={"fa fa-" + this.props.icon}></i>
</a>
)
}
});
module.exports = Psychedelicon;
До сих пор я пытался связать «это» в элемент, принимающий событие:
onMouseEnter={this.cycleColors.bind(this)}
и я получил: ` 'Вы связыванием метод компонента к компоненту. React делает это для вас автоматически высокопроизводительным способом, поэтому вы можете безопасно удалить этот вызов ».
Я также попытался:
onMouseEnter={this.cycleColors.call(Psychedelicon)}
и OnMouseEnter = {this.cycleColors.bind (Psychedelicon)}
которые оба произведены без ошибки, но не работает
Я знаю, что функция работает иначе, потому что когда я меняю
onUpdateParams:[this]
в
onUpdateParams:['.psychedelicon']
Компонент производит желаемое поведение, за исключением того, что он производит эффект все компоненты одновременно (что мне нужно, чтобы избежать необходимости, следовательно, использовать «это»).
Должно быть, что-то не хватает. Любая помощь приветствуется.
ваш второй фрагмент также не работает http://jsfiddle.net/arunpjohny/ssogpue2/1/ –
@ArunPJohny хм ... вы правы, я удалил его – HelloWorld
Попробуйте '$ ('# foo'). нажмите (Module.addClass) '! В вашем html-фрагменте вы даже не * вызываете * метод. – Bergi