问题描述
我正在尝试使用React v16.3.1加载组件时选择textarea中的所有文本
I am trying to select all the text in a textarea when a component loads using React v16.3.1
我有一个基本的样本,但 this.textarea
总是未定义,如果我更改此示例以在按钮上执行相同的代码,则单击它可以正常工作。
Following the Refs docs I have a basic sample but this.textarea
is always undefined, if I change this sample to execute the same code on a button click it works fine.
所以最新情况如何?我原本预计安装后组件应该可用吗?
So whats going on? I had expected that after mounting the component should be available?
示例代码:
import React from "react";
class Hello extends React.Component {
constructor(props) {
super(props);
this.textarea = React.createRef();
}
componentDidMount = () => {
this.textarea.current.select();
};
render() {
return (
<div>
<textarea
className="form-control"
defaultValue="the quick brown fox."
ref={this.textarea}
/>
</div>
);
}
}
来自package.json:
From package.json:
"react": "^16.3.1",
"react-dom": "^16.3.1",
谢谢
推荐答案
文件说:
下面的示例已更新为使用React 16.3中引入的React.createRef()API
。如果您使用的是早期版本的
React,我们建议改为使用回调参考。
The examples below have been updated to use the React.createRef() API introduced in React 16.3. If you are using an earlier release of React, we recommend using callback refs instead.
如果您使用较早版本发布React,你需要使用
If you are using an earlier release of React, u need use callback refs
class App extends React.Component {
constructor(props) {
super(props);
this.textarea = null;
this.setTextareaRef = element => {
this.textarea = element;
};
}
componentDidMount = () => {
if (this.textarea) this.textarea.select();
};
render() {
return (
<div>
<textarea
className="form-control"
defaultValue="the quick brown fox."
ref={this.setTextareaRef}
/>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
class App extends React.Component {
constructor(props) {
super(props);
this.textarea = React.createRef();
}
componentDidMount = () => {
this.textarea.current.select();
};
render() {
return (
<div>
<textarea
className="form-control"
defaultValue="the quick brown fox."
ref={this.textarea}
/>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://unpkg.com/react@16.3.1/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@16.3.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>
这篇关于无法访问ComponentDidMount上的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!