【问题标题】:Toggling active class on buttons in ReactJs在 ReactJs 中的按钮上切换活动类
【发布时间】: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


【解决方案1】:

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

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

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

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

最后,出于品味和偏好的考虑,您可以在定义方法时直接绑定它,而不是用this.someMethodOnMyReactComponent.bind(this) 乱扔代码。

someMethodOnMyReactComponent = (args) => {}

【讨论】:

  • 感谢您的详细解释,就像您提到的部分 this.props.children.map() 不起作用。我收到“TypeError:无法分配给 [object Object] 的只读属性 'className'”。我尝试在按钮上使用“类名”并将“活动”分配给每个按钮的类名上名为“状态”的变量,但随后我得到“类型错误:无法添加属性状态,对象不可扩展”。对此有任何解决方案的想法吗?谢谢
猜你喜欢
  • 1970-01-01
  • 2012-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-03
相关资源
最近更新 更多