我正在尝试通过参考Tutorial来实现AutoComplete的react组件。我正在使用Typescript进行开发。当我尝试破坏渲染建议方法中的状态时,TSLint编译器显示错误,提示“类型{}上不存在属性建议” 。任何人都可以帮助我克服这一问题。这是很大的帮助。
import * as React from 'react';
export default class Autocomplete extends React.Component<{},{}> {
items: string[];
constructor( props){
super(props);
this.state = {
suggestions :[],
};
this.items =['David','Damian','sara'];
}
render() {
return (
<div>
<input
type="text" onChange={this.onTextChanged}
/>
{this.renderSuggestions()}
</div>
);
}
onTextChanged = (e) =>{
console.log(e.target.value);
const value = e.target.value;
let suggestions =[];
if(value.legth>0){
const regex = new RegExp(`^${value}`,'i');
suggestions = this.items.sort().filter(v => regex.test(v));
}
this.setState(()=> ({suggestions}));
}
renderSuggestions() {
const {suggestions } = this.state;
if(suggestions.length === 0){
return null;
}
return (
<ul>
{suggestions.map((item)=> <li>{item}</li>)}
</ul>
);
}
}
答案 0 :(得分:1)
答案 1 :(得分:1)
您可以通过执行{}
在组件中指定状态为React.Component<{}>
的类型。您通常可以通过让Typescript推断状态来避免这种情况,但是当在构造函数内部分配状态时,这样做会有些问题。通常,您可以通过将它们直接分配为类
export default class Autocomplete extends React.Component {
items = ['David','Damian','sara']
state = { suggestions :[] }
// rest of your component here
}
您可以在当前类中执行此操作,因为除了设置状态外,您无需将构造函数用于设置状态,但是如果不是这样,则可以通过将打字稿分配为显式泛型参数来确保正确理解该状态像这样的组件。
interface AutocompleteState {
suggestions: Suggestion[]
}
export default class Autocomplete extends React.Component<AutocompleteState> {
constructor() {
// ...
}
}
答案 2 :(得分:0)
通过考虑所有评论和一些挣扎以及一些阅读,我使它起作用。谢谢您的所有建议。
import * as React from 'react';
import { Suggestions } from 'office-ui-fabric-react';
export interface IServiceState {
suggestions ?: string []
}
export default class Autocomplete extends React.Component<{},IServiceState> {
items =['David','Damian','sara'];
constructor( props){
super(props);
this.state = {
suggestions : [],
};
}
render() {
return (
<div>
<input
type="text" onChange={this.onTextChanged}
/>
{this.renderSuggestions()}
</div>
);
}
onTextChanged = (e) =>{
console.log(e.target.value);
const value = e.target.value;
let suggestions :string[];
if(value.length>0){
const regex = new RegExp(`^${value}`,'i');
suggestions = this.items.sort().filter(v => regex.test(v));
console.log(suggestions);
}
//this.setState(()=> ({suggestions1}));
//this.setState()
this.setState({suggestions : suggestions});
}
renderSuggestions() {
const suggestions :string[]= this.state.suggestions;
console.log('render Suggestions');
console.log(this.state.suggestions);
console.log('render1 Suggestions');
if(Suggestions.length === 0){
return null;
}
return (
<ul>
{suggestions.map((item)=> <li>{item}</li>)}
</ul>
);
}
}