【问题标题】:Typescript in React: defining a property on `this`React 中的打字稿:在 `this` 上定义一个属性
【发布时间】:2016-12-28 19:48:49
【问题描述】:

在我的非打字稿反应组件中

componentWillMount() {
    this.delayedSearch = _.debounce((val) => {
        this.onQuerySearch(val);
    }, 1000);
}

用于消除输入字段上的输入抖动。然后在输入字段上我有<input onChange={event => this.delayedSearch(e.value)}>

然而,现在,当我切换到 Typescipt 时,我对 _.debounce 的分配给了我一个错误:

Property 'delayedSearch' does not exist on type 'UserSearch'.

我该如何解决这个问题?

【问题讨论】:

    标签: javascript reactjs typescript


    【解决方案1】:

    那是因为你的类没有声明有这个delayedSearch属性,所以编译器无法理解这个属性是什么。

    在你的课堂上,你应该有类似的东西:

    class MyComponent extends React.Component<MyProps, MyState> {
        private delayedSearch: (val: string) => void;
    
        componentWillMount() {
            // should be fine now
            this.delayedSearch = _.debounce((val) => {
                this.onQuerySearch(val);
            }, 1000);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-03
      • 2021-01-07
      • 2021-12-18
      相关资源
      最近更新 更多