相关疑难解决方法(0)

React:在组件函数中未定义"this"

class PlayerControls extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      loopActive: false,
      shuffleActive: false,
    }
  }

  render() {
    var shuffleClassName = this.state.toggleActive ? "player-control-icon active" : "player-control-icon"

    return (
      <div className="player-controls">
        <FontAwesome
          className="player-control-icon"
          name='refresh'
          onClick={this.onToggleLoop}
          spin={this.state.loopActive}
        />
        <FontAwesome
          className={shuffleClassName}
          name='random'
          onClick={this.onToggleShuffle}
        />
      </div>
    );
  }

  onToggleLoop(event) {
    // "this is undefined??" <--- here
    this.setState({loopActive: !this.state.loopActive})
    this.props.onToggleLoop()
  }
Run Code Online (Sandbox Code Playgroud)

我想loopActive在切换时更新状态,但是this在处理程序中未定义对象.根据教程文档,我this应该参考该组件.我错过了什么吗?

this reactjs

121
推荐指数
4
解决办法
8万
查看次数

React - 为什么在这个例子中不需要绑定?

试图找出React的基础知识.

查看本页的第二个例子:https://facebook.github.io/react/ 我看到tick()函数设置Timer类的状态,将前一个值递增一.

class Timer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {secondsElapsed: 0};
  }

  tick() {
    this.setState((prevState) => ({
      secondsElapsed: prevState.secondsElapsed + 1
    }));
  }

  componentDidMount() {
    this.interval = setInterval(() => this.tick(), 1000);
  }

  componentWillUnmount() {
    clearInterval(this.interval);
  }

  render() {
    return (
      <div>Seconds Elapsed: {this.state.secondsElapsed}</div>
    );
  }
}

ReactDOM.render(<Timer />, mountNode);
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试实现我自己的简单Counter类时,它失败了,我得到一个控制台错误,说无法读取未定义的属性setState.

class Counter extends React.Component {
    constructor(props) {
        super(props);
        this.state = {count: 0};
    }

    increment(prevState) {
        this.setState((prevState) => ({
            count: prevState.count + 1 …
Run Code Online (Sandbox Code Playgroud)

binding reactjs

3
推荐指数
1
解决办法
2213
查看次数

标签 统计

reactjs ×2

binding ×1

this ×1