以下是用Java语言实现的简单的React App组件...
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.state = {
setting: "def",
limit: 2
}
}
updateState(element, data)
{
this.setState({ [element]: data});
}
componentDidMount()
{
this.updateState("setting", "ghi");
this.updateState("limit", 4);
}
render() {
return (
<div className="App">
<div className="App-header">
<h2>Welcome to React</h2>
</div>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
<p>
setting = {this.state.setting}, limit = {this.state.limit}
</p>
</div>
);
}
}
export default App;
请注意,updateState方法使用后期绑定来设置状态的成员。
不能在Typescript中使用相同的方法。这是打字稿中的相同组件...
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
interface IProps {
}
interface IState {
setting: string;
limit: number;
}
class App extends Component<IProps, IState> {
constructor(props: IProps) {
super(props);
this.state = {
setting: "def",
limit: 2
}
}
updateState(element: string, data: any)
{
// this.setState({ [element]: data}); // generates error
}
componentDidMount()
{
this.updateState("setting", "ghi");
this.updateState("limit", 4);
}
render() {
return(
<div className="App">
<div className="App-header">
<h2>Welcome to React</h2>
</div>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
<p>
setting = {this.state.setting}, limit = {this.state.limit}
</p>
</div>
);
}
}
export default App;
请注意,由于打字稿编译器错误,updateState的内容已被注释掉。如何在不使用switch语句的情况下解决此问题?
最佳答案
该错误可能是由于省略了属性而发生的。
使IState
中的属性为可选。
interface IState {
setting?: string;
limit?: number;
}