【问题标题】:How to properly forward a ref to a material-ui component from a functional component如何正确地将 ref 从功能组件转发到 material-ui 组件
【发布时间】:2020-03-25 21:16:38
【问题描述】:

我正在使用以下软件包为我正在处理的应用程序创建自动完成解决方案:

我正在尝试通过传入 material-ui TextareaAutosize 组件在 react-autocomplete-input 元素上使用 Component 属性。

直接从MUI传入TextareaAutosize

import {TextareaAutosize} from '@material-ui/core';
<AutocompleteInput Component={TextareaAutosize} />

这可行,但是我无法控制它获得的道具。

通过自定义组件,我可以添加道具

const CustomTextarea = forwardRef((props, ref) => (
  // If I don't forward the ref I get an error...
  <TextareaAutosize
    placeholder="Material-ui through custom component..."
    ref={ref}
  />
));

<AutocompleteInput Component={CustomTextarea} />

这会使自动完成功能完全停止工作。但是,占位符仍然正确显示,这意味着道具至少可以通过。

您可以在下面的沙箱中查看所有示例。

示例: https://codesandbox.io/s/frosty-wildflower-48iyd

【问题讨论】:

    标签: javascript reactjs material-ui react-forwardref


    【解决方案1】:

    你只是错过了传递默认的props

    const CustomTextarea = forwardRef((props, ref) => (
      // If I don't forward the ref I get an error...
      <TextareaAutosize
        placeholder="Material-ui through custom component..."
        {...props} // here
        ref={ref}
      />
    ))
    

    【讨论】:

      猜你喜欢
      • 2022-11-14
      • 2020-06-29
      • 2020-02-26
      • 2019-10-19
      • 1970-01-01
      • 1970-01-01
      • 2020-01-29
      • 2021-05-13
      • 2019-11-21
      相关资源
      最近更新 更多