2017-06-03 1 views
1

これは同じ問題ですか、何か不足していますか?私はインターフェイスで定義されたMyComponentのための私の小道具を持っている場合は残りの小道具を反応コンポーネントに渡すにはどうすればいいですか?また、インターフェイスに必要な小道具を定義しています

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 

することは、私は次のエラーを取得する:

エラーTS2339:プロパティ「のonChange」タイプに「IntrinsicAttributes &小道具を」は存在しません。

しかし、私がpropsの型をanyに変更しても、それはうまくコンパイルされます。

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自体に使用することが少なく、安全になります。

関連する問題