2

我正在尝试使用 ref 来访问 InputText 组件的底层输入元素。我曾经this.textFieldRef = React.createRef()设置 ref,然后设置属性ref={this.textFieldRef}来连接它。然而,在componentDidMountI cannot use this.textFieldRef.current.select()because select()is not a function available for that object 中。所以不知何故,InputText 没有返回底层的 HTMLInputElement。

有谁知道我如何从 ref 获取允许我访问select()InputText 元素中的文本的内容?

这是我的代码,实际上是在 TypeScript 中...

import * as React from 'react';
import { InputText } from 'primereact/inputtext';

export class ValueCard extends React.Component<{}, {}> {

  textFieldRef: React.RefObject<any> = React.createRef();

  componentDidMount = () => {
    if (this.textFieldRef.current instanceof InputText) {
      this.textFieldRef.current.select();
    }
  }

  render() {
    return = (
      <InputText
        value="test"
        ref={this.textFieldRef}
      />
    );
  }
}
4

2 回答 2

1

查看 PrimeReactInputText组件的源代码(sourceinput ),他们将对内部元素的引用附加到this.element. 这允许您只添加.element到您的参考:

this.textFieldRef.current.element.select();

我在这个沙箱中对其进行了测试,它似乎按预期工作: https ://codesandbox.io/s/203k7vx26j

于 2019-01-18T23:42:39.170 回答
1

也许您可以尝试使用react-dom库:

ReactDOM.findDOMNode(this.textFieldRef.current).querySelector('input');
于 2020-08-18T14:12:42.600 回答