我试图使用ref来获取InputText组件的基础输入元素。我使用了public class IntArrayList {
private int[] a;
private int length;
private int index;
private int count;
public IntArrayList() {
length = 0;
a = new int[4];
}
public int get(int i) {
if (i < 0 || i >= length) {
throw new ArrayIndexOutOfBoundsException(i);
}
return a[i];
}
public int size() {
return length;
}
public void set(int i, int x) {
if (i < 0 || i >= a.length) {
throw new ArrayIndexOutOfBoundsException(i);
}
a[i] = x;
}
public void add(int x) {
if (length >= a.length) {
int[] b = new int[a.length * 2];
for (int i = 0; i < a.length; i++) {
b[i] = a[i];
}
a = b;
//count += 1;
}
a[length] = x;
count++;
length = length + 1;
}
public void addBefore(int x) {
int[] b = new int[a.length*2];
for (int i = 0; i < a.length; i++) {
b[i+a.length] = a[i];
}
a = b;
a[index] = x;
length ++;
}
}
来建立引用,然后使用属性this.textFieldRef = React.createRef()
来进行引用。但是在ref={this.textFieldRef}
中我不能使用componentDidMount
,因为this.textFieldRef.current.select()
不是该对象可用的函数。因此,以某种方式,InputText不会返回基础HTMLInputElement。
有人知道我如何从引用中获取使我可以select()
InputText元素中的文本吗?
这是我的代码,实际上是在TypeScript中...
select()
答案 0 :(得分:1)
也许您可以尝试使用react-dom
库:
ReactDOM.findDOMNode(this.textFieldRef.current).querySelector('input');
答案 1 :(得分:0)
查看PrimeReact的InputText
组件(source)的来源,他们将对内部input
元素的引用附加到this.element
。
这样一来,您只需将.element
添加到参考中即可
this.textFieldRef.current.element.select();
我在此沙箱中对其进行了测试,它似乎可以按预期工作: https://codesandbox.io/s/203k7vx26j