如何向forwardRef传递Props?组件传参失效问题求助
问题
我使用forwardRef将一个库组件传入另一个库组件,需要为这个forwardRef传递文本输入框的label等Props,但Props始终未从父组件AutocompleteDropdown传递过来。尝试将forwardRef作为函数传递无效,以带Props的组件形式传递时还出现错误:Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.
代码如下:
const SelectorInput = forwardRef((props, ref) => { return ( <TextInput {...props} ref={ref} label={props.label} mode="outlined" outlineColor="#68c25a" activeOutlineColor="#68c25a" style={styles.sheepTextInput} onSelectItem={(value) => setFieldValue(props.field, value.id)} /> ); }); <AutocompleteDropdown InputComponent={SelectorInput} ref={searchRef} label="foobar" dataSet={suggestionsList} {/* 其他相关Props */} />
解决方案
- 确认
AutocompleteDropdown的API规则:多数这类组件会通过专门的属性(比如inputProps,不同库命名可能有差异)将额外参数传递给InputComponent,而非直接把自身Props自动传给子组件。你需要通过这类属性传递label等需要的参数。 - 清理冗余代码:
{...props}已经会展开所有传入的Props,包括label,所以label={props.label}属于冗余写法,直接去掉即可,避免潜在的Props覆盖问题。 - 确保传递组件而非实例:
InputComponent必须传入组件本身(函数或类),不能传入渲染后的React元素(比如<SelectorInput label="xxx" />),后者会返回对象,触发你遇到的类型错误。
修正后的代码示例:
const SelectorInput = forwardRef((props, ref) => { return ( <TextInput {...props} ref={ref} mode="outlined" outlineColor="#68c25a" activeOutlineColor="#68c25a" style={styles.sheepTextInput} onSelectItem={(value) => setFieldValue(props.field, value.id)} /> ); }); <AutocompleteDropdown InputComponent={SelectorInput} ref={searchRef} dataSet={suggestionsList} // 通过inputProps传递需要的参数给SelectorInput inputProps={{ label: "foobar", field: "targetFieldName" }} {/* 其他相关Props */} />
内容的提问来源于stack exchange,提问作者Nika Bo
相关产品推荐
相关产品推荐

