Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在react中获取prevstate而不使用es6脚本_Javascript_Reactjs_Ecmascript 6_React Redux_React Dom - Fatal编程技术网

Javascript 在react中获取prevstate而不使用es6脚本

Javascript 在react中获取prevstate而不使用es6脚本,javascript,reactjs,ecmascript-6,react-redux,react-dom,Javascript,Reactjs,Ecmascript 6,React Redux,React Dom,我编写了一些脚本,当我们在reactjs中单击按钮时,它将计算数字。这是我的剧本: var ComponentCounter = React.createClass({ getInitialState: function() { return {count: 1}; }, doIncrement:function(){ this.setState(function(prevState,currentProps){ return {

我编写了一些脚本,当我们在reactjs中单击按钮时,它将计算数字。这是我的剧本:

var ComponentCounter = React.createClass({
    getInitialState: function() {
    return {count: 1};
  },
  doIncrement:function(){
    this.setState(function(prevState,currentProps){
        return {
        count:prevState.count+1
      };
    });
  },
  doDecrement:function(){
    this.setState(function(prevState,currentProps){
        return {
        count:prevState.count-1
      };
    });
  },
    render: function(){
    return(
        <div>
            <Button onClick={this.doIncrement}>+</Button>
            <h2>{this.state.count}</h2>
            <Button onClick={this.doDecrement}>-</Button>
      </div>);  
  }
});
ReactDOM.render(<ComponentCounter/>,document.getElementById('counter'));
var ComponentCounter=React.createClass({
getInitialState:函数(){
返回{count:1};
},
doIncrement:function(){
this.setState(函数(prevState、currentProps){
返回{
计数:prevState。计数+1
};
});
},
doDecrement:function(){
this.setState(函数(prevState、currentProps){
返回{
计数:prevState.count-1
};
});
},
render:function(){
返回(
+
{this.state.count}
-
);  
}
});
ReactDOM.render(,document.getElementById('counter'));
但当我点击按钮时,它也不起作用

你能修好它并解释原因吗


谢谢:)

您应该将上下文绑定到单击处理程序方法。否则,当函数实际被调用时,该方法内部的
将不再指向组件实例。所以你应该这样做:

   <Button onClick={this.doIncrement.bind(this)}>+</Button>
   <h2>{this.state.count}</h2>
   <Button onClick={this.doDecrement.bind(this)}>-</Button>
+
{this.state.count}
-

如果@Bartek的答案没有解决您的问题,那么另一个需要关注的领域是您的
按钮
组件。。。是否将
onClick
道具传递给实际的DOM元素

var Button = createClass({
   ...
   render: function() {
     return <button onClick={this.props.onChange}>{this.props.children}</button>;
     //or
     return <button {...this.props} />;
   }
});
var按钮=createClass({
...
render:function(){
返回{this.props.children};
//或
返回;
}
});

oops我忘了按钮标签是我的反应组件..v.你的问题解决了吗?