gpt4 book ai didi

javascript - 在 ReactJs 中切换按钮上的事件类

转载 作者:行者123 更新时间:2023-11-28 06:53:59 24 4
gpt4 key购买 nike

我正在尝试切换 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(…)

react 版本:0.14-rc1

如果指出我的错误并寻求解决方案,我将不胜感激。非常感谢。

最佳答案

首先,this.children 应该是 this.props.children。 (注意,如果您动态传递子项,则需要记住,仅传递 1 个子项不会像传递多个子项时那样产生数组,因此 this. props.children.map() 将不起作用。)

其次,this.props 和简洁的 this.context 不会填充到类的构造函数中除非 您将 props 传递给 constructorsuper。因此,要么传递它们,要么将其完全移出构造函数,这是可行的方法。

class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
active: this.props.active || 0
}
}
}

第三,在不知道 Link.handleClick 是什么的情况下,如果修复上述问题,您的代码应该可以工作。

最后,根据品味和偏好,您可以在定义方法时直接绑定(bind)它,而不是用 this.someMethodOnMyReactComponent.bind(this) 乱七八糟地使用代码。

someMethodOnMyReactComponent = (args) => {}

关于javascript - 在 ReactJs 中切换按钮上的事件类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32721394/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com