我正在尝试在单击每个组件时触发事件。谁能告诉我最好的方法呢?此刻,自定义方法无法启动。有人可以帮忙吗?
var MessageTypeNavigation = React.createClass({
displayName : 'MessageTypeNavigation',
// method I want to fire on each click
_clearBasket: function(){
console.log('clear basket');
},
_getPrimaryTabs: function(){
if(this.props.hidePrimaryTabs) return [];
var active = this.props.activeSection;
return [
<TabLink onClick={_clearBasket} isActive={active === 'general'} key="general" route="general-contacts" label="General" />,
<TabLink onClick={_clearBasket} isActive={active === 'attendance'} key="attendance" route="attendance-contacts" label="Attendance" />,
<TabLink onClick={_clearBasket} isActive={active === 'lateness'} key="lateness" route="temp" label="Lateness" />,
<TabLink onClick={_clearBasket} isActive={active === 'detention'} key="detention" route="temp" label="Detention" />,
<TabLink onClick={_clearBasket} isActive={active === 'behaviour'} key="behaviour" route="behaviour" label="Behaviour" />,
<TabLink onClick={_clearBasket} isActive={active === 'achievements'} key="achievements" route="achievements" label="Achievements" />
];
},
render: function() {
return (
<div>
<div>
<ul className="tabs">
{this._getPrimaryTabs()}
</ul>
</div>
</div>
);
},
});
嵌套的tabLink组件:
var TabLink = React.createClass({
contextTypes: {
router: React.PropTypes.func
},
getTabClass: function () {
return this.props.isActive ? "active_on" : "";
},
getLinkNode: function() {
if (this.props.link) return <a href={this.props.link}>{this.props.label}</a>;
return <Link to={this.props.route}>{this.props.label}</Link>;
},
render: function () {
return (
<li className={this.getTabClass()}>
{this.getLinkNode()}
</li>
);
}
});
module.exports = TabLink;
答案 0 :(得分:3)
_clearBasket
是您组件的成员,而不是全局函数。要引用它,您应该使用this._clearBasket
:
<TabLink onClick={this._clearBasket}
isActive={active === 'general'}
key="general" route="general-contacts" label="General" />,
onClick
。它只适用于dom元素。您必须自己为TabLink
组件实现它。你应该改变:
<li className={this.getTabClass()}>
{this.getLinkNode()}
</li>
为:
<li className={this.getTabClass()} onClick={this.props.onClick}>
{this.getLinkNode()}
</li>
此处,onClick
本身是为<li/>
元素定义的。 this.props.onClick
是您传递到TabLink
组件中MessageTypeNavigation
的函数。该函数又与_clearBasket
绑定。