我開始使用 React,我看到我可以使用 setInterval() 中的粗箭頭函數設置一個時鐘:class Clock extends React.Component { constructor(props) { super(props) this.state = { date: new Date() } this.timer = null } componentDidMount() { this.timer = window.setInterval(() => { this.setState({ date: new Date() }) }, 1000) }但是我沒有設法通過常規函數(如下)獲得相同的結果。我認為它與在常規函數內創建新上下文的“this”關鍵字相關聯?我不知道如何解決這個問題:componentDidMount() { this.timer = window.setInterval(function() { this.setState({ date: new Date() }) }, 1000)}感謝您的時間
沒有胖箭頭功能的 JavaScript React setInterval
神不在的星期二
2023-06-15 09:51:28