[英]While Dynamically Creating menu items with react and material-ui why does onTouchStart auto executes function
第一次发帖,我很高兴地说我终于有话要问! 我要求进一步加深对JavaScript
& React
理解,并感谢所有反馈。
我当前正在编写一些前端代码,并且已经用material-ui
创建了leftNav。 在创建菜单时,我以为我会测试我对javascript的理解并做出反应,并努力编写一个将创建菜单的函数,而不必在jsx中编写<MenuItem props={}> </MenuItem>
一遍又一遍,这很简单,我很高兴能使其正常工作。 这是react组件内部的render
方法:
<LeftNav className={'animated ' + this.state.animation}
open={this.props.open}
style={style.leftNav}
width={220}
key={0}>
<Card style={style.card}>
<CardHeader avatar={null}
style={style.cardHeader}
zDepth={2}>
<Avatar size={65}
style={style.avatar}
src={avatarUrl}
onClick={ this._handleOpenSnackbar}/>
</CardHeader>
</Card>
<br/>
{this._createMenu() }
</LeftNav>
{this._createMenu() }
将创建我需要的所有MenuItem
,并且一切看起来都很完美,直到我需要向每个项目(obv)添加点击事件处理程序为止。 如果我只是在jsx中将<MenuItem props={}> </MenuItem>
堆叠在一起,那会更简单。
我刚刚添加了一个开关菜单来测试属性,但是现在onTouchTap={_routeHandler.call(prop)}
正在executing
最后一个测试用例并自动路由,而不仅仅是单击时路由。 在我看来,我认为每个MenuItem
都有其各自的click事件处理程序,并且它们确实做到了,但是尽管有break
,但最后一个测试用例始终执行。
我通过返回一个匿名函数,然后做取决于被传递到一些道具守护路由解决了问题this
对上下文_routeHandler()
我要问的是,为什么要用开关箱返回一个匿名函数才能使onTapTouch
事件起作用? 我认为onTapTouch仅在单击MenuItem
时才会触发。
我很困惑,并假设我还没有完全理解React的一些内部工作原理。
下面是动态创建菜单的method
。
欢迎任何反馈。
谢谢
_createMenu = () => {
let menuOptionsAndIcons = {
'About me': <i className="fa fa-male" style={style.icons}/>,
'Skills': <i className="fa fa-certificate" style={style.icons}/>,
'Music': <i className="fa fa-music" style={style.icons}/>,
'Interests': <i className="fa fa-cogs" style={style.icons}/>
},
menu = [];
function _routeHandler() {
switch (this) {
case 'About me':
return function () {
if (typeof window !== 'undefined')
window.location.href = '' + 'http://' + window.location.host + '/about_me';
};
break;
case 'Skills':
return function () {
if (typeof window !== 'undefined')
window.location.href = '' + 'http://' + window.location.host + '/skills';
};
break;
case 'Music':
return function () {
if (typeof window !== 'undefined')
window.location.href = '' + 'http://' + window.location.host + '/music';
};
break;
case 'Interests':
return function () {
if (typeof window !== 'undefined')
window.location.href = '' + 'http://' + window.location.host + '/interests';
};
break;
default:
break;
}
}
for (var prop in menuOptionsAndIcons) {
if (menuOptionsAndIcons.hasOwnProperty(prop)) {
menu.push(<MenuItem leftIcon={menuOptionsAndIcons[prop]}
primaryText={ prop }
style={style.menuItem}
onTouchTap={_routeHandler.call(prop)}
key={prop}
rippleColor={"#FFFAE8"}
className="animated fadeInLeft"/>)
}
}
return menu
};
在事件处理程序中,您应该这样使用
onClick={()=>this.yourfunction()}
不
onClick={this.yourfunction()}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.