2017-06-03 66 views
1

所以这是同一个问题,还是我只是想念一些东西?如何通过其余的道具来反应组件,同时也需要在界面中定义道具

import * as React from 'react'; 

interface Props { 
    value: string; 
} 

const MyComponent = (props: Props) => { 
    const { value, ...rest } = props; 

    return (
     <input {...rest} type="text" value={value} /> 
    ); 
} 

interface ParentState { 
    searchText: string; 
} 

class ParentComponent extends React.Component<{}, ParentState> { 
    state: ParentState = { 
     searchText: '' 
    }; 

    onSearchTextChanged = (e: React.FormEvent<HTMLInputElement>) => { 
     this.setState({ 
      searchText: e.currentTarget.value 
     }); 
    } 

    render() { 
     const { searchText } = this.state; 

     return (
      <div> 
       <h2>Some Text</h2> 
       <MyComponent value={searchText} onChange={this.onSearchTextChanged} className="search-input" placeholder="Enter text"/> 
// Errors here 
      </div> 
     ) 
    } 
} 

export default ParentComponent 

当我有我的MyComponent的道具接口中定义的,我得到以下错误:

错误TS2339:房产“的onChange”上键入“IntrinsicAttributes &道具”不存在。

但是,如果我改变道具类型为任何,它编译就好了。

const MyComponent = (props: any) => { 

是否有可能定义道具的接口,以便有需要特定的道具,也让更多的道具中传递,因此我没有明确地将它们添加到界面?

我正在使用TypeScript 2.3.4和React 15.5.4。

回答

0

你能避免过多的财产/添加一个字符串指数签名你的接口属性检查:

interface Props { 
    value: string; 

    // This is a string index signature. 
    // This means that all properties in 'Props' are assignable to 
    // the empty object type ({}) 
    [propName: string]: {}; 
} 

你也可以写[propName: string]: any但通常使得它不太安全的MyComponent使用本身。