繁体   English   中英

onClick事件在ReactJS中不起作用

[英]onClick event doesn't act in ReactJS

我在onClicke事件中有一个React代码。 我想得到function(someFunction)的实现。 运行此代码没有任何错误,其他所有工作正常。 我想问题可能出在功能上。 React代码是

    class Hello extends Component {
  constructor() {
    super();
    this.num = { number: 4 };
    this.someFunction = this.someFunction.bind(this);
  }

  someFunction() { this.setState({ number: this.num.number + 3 }); }

  render() {
    const coco = {
      color: 'blue',
      background: 'yellow',
      width: '200px',
      height: '200px',
      padding: 'lem'
    };

    return (<div style={coco} onClick={this.someFunction}>
      <p style={coco} onClick={this.someFunction}> bly blya
        Hello {this.props.name} </p>
      <p style={coco} onClick={this.someFunction} >
        Current count: {this.num.number + 3}
      </p>
    </div>)
  }
}

render(<Hello/>, document.getElementById('container'));

您应该替换:

Current count: {this.num.number + 3} 

有:

Current count: {this.state.num.number + 3}

而不是定义this.num ,您应该在构造函数中定义组件的初始状态:

this.state = {
  number: 4,
};

您的函数会在click回调上正确调用,但是更新状态的逻辑不起作用,因为它总是返回相同的状态。 this.num.number的值始终为4,因此在调用setState之后,状态的值始终为7。

您可以使用以前的状态来计算新状态,如下所示:

this.setState((prevState) => {
    return {
        number: prevState.number + 3
    };
});

看到这个JSFiddle

实际上它工作得很好,你的组件没有更新,因为它不依赖于state在你havne't定义的任何事实stateconstructor ,这可能是一个错字..

import React , {Component} from 'react'
import ReactDOM from 'react-dom'

class Hello extends Component {
  constructor() {
    super();
    // defining state 
    this.state = { number: 4  };
    this.someFunction = this.someFunction.bind(this);
  }

  someFunction() { 
    //chnaging state case re-render for component 
    this.setState({number: this.state.number + 3 }); 
  }

  render() {
    const coco = {
      color: 'blue',
      background: 'yellow',
      width: '200px',
      height: '200px',
      padding: 'lem'
    };

    return (
      <div style={coco} onClick={this.someFunction}>
        <p style={coco} onClick={this.someFunction}> bly blya
          Hello {this.props.name} </p>
        <p style={coco} onClick={this.someFunction} >
          Current count: {this.state.number + 3 /*need to use state here .  */}
        </p>
      </div>
    )
  }
}

ReactDOM.render(<Hello/>, document.getElementById('container')); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM