【发布时间】:2015-09-22 15:52:26
【问题描述】:
我正在尝试在 ReactJs 的按钮组中切换活动类。我遵循了某人发布的示例,但似乎无法使其正常工作。以下是我的代码:
class ButtonGroup extends React.Component {
constructor() {
super();
this.state = {
active: this.props.active || 0
};
}
clickHandler(e) {
var nodes = Array.prototype.slice.call( e.currentTarget.children );
var index = nodes.indexOf( e.target );
e.preventDefault();
this.setState({ active: index });
}
render() {
var buttons = this.children.map(function(child, i) {
if (i === this.state.active) child.props.className += ' active';
return child;
}, this)
return (
<div className="ButtonGroup" onClick={this.clickHandler.bind(this)}>
{ buttons }
</div>
)
}
}
class Nav extends React.Component {
render() {
return (
<ButtonGroup>
<a onClick={Link.handleClick} href="/profile" className="MenuLink active">Profile</a>
<a onClick={Link.handleClick} href="/profile/works" className="MenuLink">Works</a>
<a onClick={Link.handleClick} href="/profile/activity" className="MenuLink">Activity</a>
<a onClick={Link.handleClick} href="/profile/following" className="MenuLink">Following <span className="FollowCount">{this.props.following}</span></a>
<a onClick={Link.handleClick} href="/profile/followers" className="MenuLink">Followers <span className="FollowCount">{this.props.followers}</span></a>
</ButtonGroup>
);
}
}
我得到的错误:
Unhandled promise rejection TypeError: Cannot read property 'active' of undefined(…)
反应版本:0.14-rc1
如果我的错误被指出并解决这个问题,我将不胜感激。非常感谢。
【问题讨论】:
-
报错是哪一行?确保
this设置正确。 -
很难弄清楚它指的是哪一行。它显示:es6.promise.js:108
-
打开浏览器的开发者工具并启用“异常中断”(必要时也可以中断捕获的异常)。
-
现在得到“未处理的承诺拒绝类型错误:this.props is undefined”所以它必须是第 6 行
-
我没有使用 es6 类的新反应,但尝试查看该构造函数,
this.props可能尚不可用
标签: javascript reactjs