javascript - 如何将外部引用传递给 Material UI 自动完成组件?
问题描述
使用 Material UI 4.11.1,Autocomplete有一个renderInput
渲染输入元素的方法,例如通常是一个TextField
组件,但是它已经提供了ref
值inputProps
。因此,覆盖ref
prop 将导致Autocomplete
失败,因为它的原始 prop 从未从输入元素接收到值,它是null
.
那么,如何获取组件ref
生成的Autocomplete
内容并将其提供给父级?
本质上 :
const LocalAutoComplete = forwardRef(({
loading,
options,
TextFieldProps,
...props
}, ref) => {
const {
inputProps: userinputProps = {},
InputProps: userInputProps = {},
...userTextFieldProps
} = TextFieldProps || {};
return (
<Autocomplete
freeSolo
{ ...props }
loading={loading}
disablePortal={ false }
options={options}
PaperComponent={CustomPaper}
renderInput={({
inputProps: paramsinputProps, // ref = paramsInputProps.ref ???
InputProps: paramsInputProps,
...paramsTextFieldProps
}) => (
<TextField
{...paramsTextFieldProps}
{...userTextFieldProps}
InputProps={{
...paramsInputProps,
...userInputProps,
endAdornment: (<>
{loading ? <CircularProgress color="inherit" size={20} /> : null}
{paramsInputProps.endAdornment}
</>),
}}
inputProps={{
...paramsinputProps,
...userinputProps
}}
/>
)}
/>
);
});
总之,有paramsInputProps.ref === ref
,不知何故。
** 更新 **
这似乎有效,但肯定有更好的方法!
const LocalAutoComplete = forwardRef(({
loading,
options,
TextFieldProps,
...props
}, ref) => {
const wtfRef = useRef();
const {
inputProps: userinputProps = {},
InputProps: userInputProps = {},
...userTextFieldProps
} = TextFieldProps || {};
// lolz...
useImperativeHandle(ref, () => wtfRef.current?.current, []);
return (
<Autocomplete
freeSolo
{ ...props }
loading={loading}
disablePortal={ false }
options={options}
PaperComponent={CustomPaper}
renderInput={({
inputProps: {
ref,
...paramsinputProps
},
InputProps: {
endAdornment,
...paramsInputProps
},
...paramsTextFieldProps
}) => (
<TextField
{...paramsTextFieldProps}
{...userTextFieldProps}
InputProps={{
...paramsInputProps,
...userInputProps,
endAdornment: (<>
{loading ? <CircularProgress color="inherit" size={20} /> : null}
{endAdornment}
</>),
}}
inputProps={{
ref: wtfRef.current = ref, // lolz again...
...paramsinputProps,
...userinputProps
}}
/>
)}
/>
);
});
解决方案
推荐阅读
- node.js - 在 Node js 中实现条带时的身份验证错误
- ruby-on-rails - 如何在 ruby on rails 中设置像 amp-email 这样的动态电子邮件?
- javascript - 在javascript中实现快速排序算法的比较计数器
- java - 如何删除我的代码中的重复整数?
- swift - 我应该如何在相同的操作中设置按钮的图像?
- php - PHP Slim 3 API 中间件类不能来自 __invoke 的方法?
- mysql - 相同记录集上的相同 UPDATE SQL 似乎与 MariaDB 行为不端
- node.js - google sheet api v4 在特定行之后附加行或将行移动到特定位置
- python - 如何将注释箭头添加到图例
- haskell - 我可以用“递归方案”“cata”来写“foldr”(或“foldMap”)吗?