[英]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定義的任何事實state
在constructor
,這可能是一個錯字..
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.