首页 文章

将自定义道具传递给TypeScript中的Redux Form Field

提问于
浏览
9

我想将自定义属性传递给我的Redux-Form-Field . 在文档中它说:

传递给Field的任何自定义道具都将合并到与输入和元对象相同级别的props对象中 .

但是将自定义道具传递给Field组件会引发编译错误:

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

属性'myProp'在类型'上不存在(IntrinsicAttributes&IntrinsicClassAttributes>&...

在props属性中,我只能添加一组预定义的属性,如占位符或类型 . 传递另一个道具会抛出此错误:

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

输入'{name:“E-Mail”; component:(props:any)=>元素;道具:{myProps:string; }; }'不能赋值给''(IntrinsicAttributes&...

是否有可能将自定义道具传递给TypeScript中的Field组件?

2 回答

  • 7

    经过一些实验,我找到了传递自定义道具的解决方案:

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

    在myComponent中,您可以在属性的根级别拥有自定义道具:

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

    我'm not a Typescript user, so I'我不确定类型定义是如何工作的,但我找到了this thread about type definitions for Redux-form v6 . 最后,它们链接到this repository,它应该具有(如果我理解正确的话)更新的类型定义 .

    我想另一种选择是切换到vanilla JS来实现这一特定功能 . 或者也许可以定义一个获取自定义prop的函数,然后返回一个准备好接受Redux表单道具并合并它们的组件 .

    Edit :我试图在下面的代码中说明最后一个建议的基本思想,即所谓的HOC(高阶组件) .

    const inputWithCustomFields = (customFields) => ComponentToGetExtraFields => (props) => {
    	const mergedProps = {...props, ...customFields};
    	return (<ComponentToGetExtraFields {...mergedProps} />);
    };
    
    const ComponentThatNeedsCustomStuff = ({myCustomField1, myCustomField2, ...rest}) => {
    	console.log('doing stuff with the custom props',myCustomField1, myCustomField2);
    	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>
    

相关问题