2017-09-08 35 views
6

我想將自定義屬性傳遞給我的Redux-Form-Field。在本文檔中,它說:將自定義道具傳遞到TypeScript中的Redux Form字段

Any custom props passed to Field will be merged into the props object on the same level as the input and meta objects.

但通過自定義道具字段組件將拋出一個編譯錯誤:

<Field 
    name="E-Mail" 
    component={MaterialTextField} 
    myProp="Test" 
/> 

住宅「myProp」上類型不存在「(IntrinsicAttributes & IntrinsicClassAttributes> & ...

在props屬性中,我只能添加一組預定義的屬性,如placeholder或type。傳遞另一個prop會拋出這個錯誤:

<Field 
    name="E-Mail" 
    component={MaterialTextField} 
    props = {{ 
     myProps: 'Test' 
    }} 
/> 

輸入'{name:「E-Mail」; component:(props:any)=> Element;道具:{myProps:string; }; }「不能分配到類型」(IntrinsicAttributes & ......

有沒有通過自定義道具字段部件在打字稿的可能性?

+0

你有'redux-form'和'react-redux-form '但這些實際上是兩種不同的框架。你指的是哪一個? –

+0

我的不好,我指的是redux-form。 – Deutro

回答

3

經過一些嘗試在我身邊,我找到了一個解決方案,通過定製的道具:

<Field 
    name="myName" 
    props={{ 
     type: 'text' 
    }} 
    component={myComponent} 
    {...{ 
     myCustomProps1: 'myCustomProp1', 
     myCustomProps2: 'myCustomProp2' 
    }} 
/> 

在myComponent的你有你的屬性的根級別自定義道具:

const myComponent = (props) => { 
    return <div>{props.myCustomProp1 + " " props.myCustomProp2}</div> 
} 
0

我不是一個打字稿用戶,所以我不但我發現this thread about type definitions for Redux-form v6。最後他們鏈接到this repository這應該有(如果我理解正確的話)更新的類型定義。

我想另一種方法是切換到香草JS對於這個特定的功能,或者也許可以定義一個函數,它接受你的自定義道具,然後返回一個準備採用紅色ux形成道具併合並它們。

編輯:我試着在下面的包含代碼中說明最後一個建議(所謂的HOC(高階組件))的基本概念。

const inputWithCustomFields = (customFields) => ComponentToGetExtraFields => (props) => { 
 
\t const mergedProps = {...props, ...customFields}; 
 
\t return (<ComponentToGetExtraFields {...mergedProps} />); 
 
}; 
 

 
const ComponentThatNeedsCustomStuff = ({myCustomField1, myCustomField2, ...rest}) => { 
 
\t console.log('doing stuff with the custom props',myCustomField1, myCustomField2); 
 
\t return (<div><h1>{myCustomField1 + myCustomField2}</h1><input {...rest} /></div>); 
 
} 
 

 
const Parent =() => { 
 
    const myCustomFields = { 
 
    myCustomField1: "Hello, ", 
 
    myCustomField2: "world!", 
 
    value: 'can\'t change me', 
 
    onChange:() => { /* do nothing */ } 
 
    }; 
 
    const MergedComponent = inputWithCustomFields(myCustomFields)(ComponentThatNeedsCustomStuff); 
 
    return (<div> 
 
     <MergedComponent /> 
 
    </div>); 
 
}; 
 

 
ReactDOM.render(<Parent />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 
 
<div id="root"></div>

+0

雖然這個鏈接可能回答這個問題,但最好在這裏包含答案的重要部分,並提供供參考的鏈接。如果鏈接頁面更改,則僅鏈接答案可能會失效。 - [來自評論](/ review/low-quality-posts/17271977) – ReactiveRaven

+0

夠公平的。對剩餘的鏈接(太多的代碼/文本要複製等等)不能做太多的工作,但我爲一個以前只是模糊地指向鏈接內容的部分添加了一個代碼示例。 – jonahe

相關問題