gpt4 book ai didi

javascript - 我如何通过教程在 tsx 中实现?

转载 作者:行者123 更新时间:2023-11-30 12:02:54 25 4
gpt4 key购买 nike

教程来源:有状态组件 - https://facebook.github.io/react/

这是我的代码:

interface Props {

}

interface State {
secondsElapsed: number,
}


class Timer extends React.Component<Props, State> {
private interval: number;

getInitialState() {
return { secondsElapsed: 0 };
}
tick() {
this.setState({ secondsElapsed: this.state.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 />,
document.getElementById('example')
);

在 html 中,它返回 timer.js:26 Uncaught TypeError: Cannot read property 'secondsElapsed' of null。为什么 secondsElapsed 为空?

发生了什么事?

最佳答案

React ES6 类没有 getInitialState 方法。此方法只有由 React.createClass({})

创建的组件

在 React 类中,您可以在构造函数中手动设置状态:

constructor() {
super();
this.state = {
secondsElapsed: 0
};
}

React docs about ES6-classes

关于javascript - 我如何通过教程在 tsx 中实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36193096/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com