如何封装包含admin-on-rest ReferenceInput的组件?排查缺失内容
解决admin-on-rest中封装ReferenceInput组件的"Cannot read property 'value' of undefined"错误
嘿,我看你在封装admin-on-rest的ReferenceInput组件时碰到了那个让人头疼的Cannot read property 'value' of undefined错误,我来帮你找出问题所在!
问题根源
你在封装的Prueba组件里,把所有接收到的props一股脑传递给了ReferenceInput和AutocompleteInput,但这里面很多props是来自Create或SimpleForm的,并不是这两个组件真正需要的。这种做法会覆盖组件内部从表单上下文获取的关键属性(比如input对象),导致组件找不到input.value,从而抛出这个错误。
修正后的代码
你只需要给子组件传递它真正需要的配置项,而不是全部props。比如这样写:
// 正确的封装方式 export const commentsCreate = (props) => ( <Create title="Create" {...props} > <SimpleForm> <Prueba /> </SimpleForm> </Create> ); const Prueba = () => ( <ReferenceInput label="Posts" source="field" reference="posts" allowEmpty> <AutocompleteInput optionText="name" /> </ReferenceInput> );
如果你确实需要传递一些特定的表单相关props(比如自定义的权限配置等),可以解构出不需要的部分,只传递必要的:
// 按需传递props的版本 export const commentsCreate = (props) => ( <Create title="Create" {...props} > <SimpleForm> <Prueba /> </SimpleForm> </Create> ); const Prueba = ({ someCustomProp, ...rest }) => ( <ReferenceInput label="Posts" source="field" reference="posts" allowEmpty {...rest} // 只传递组件需要的额外props > <AutocompleteInput optionText="name" /> </ReferenceInput> );
为什么这样能解决问题
admin-on-rest的表单组件(包括ReferenceInput)是通过内部的表单上下文来获取input、meta这些核心属性的,这些属性是组件正常工作的关键。当你把上层组件的全部props传递下来时,会干扰这个上下文的属性注入,导致组件找不到input.value。只传递组件的配置项(比如label、source),就能让组件正常从上下文获取它需要的状态属性啦。
内容的提问来源于stack exchange,提问作者Fernando Navarro
相关产品推荐
相关产品推荐

