ref
作者:
苍老师的眼泪 | 来源:发表于
2022-08-03 06:24 被阅读0次import React from 'react';
import ReactDOM from 'react-dom/client';
class AutoFocusTextInput extends React.Component {
constructor(props) {
super(props)
this.ref = React.createRef()
}
componentDidMount() {
this.ref.current.focusTextInput()
}
render() {
return (
<div>
<CustomTextInput ref={this.ref}></CustomTextInput>
</div>
)
}
}
class CustomTextInput extends React.Component {
constructor(props) {
super(props);
// 创建一个 ref 来存储 textInput 的 DOM 元素
this.textInput = React.createRef();
this.focusTextInput = this.focusTextInput.bind(this);
}
focusTextInput() {
// 直接使用原生 API 使 text 输入框获得焦点
// 注意:我们通过 "current" 来访问 DOM 节点
this.textInput.current.focus();
}
render() {
// 告诉 React 我们想把 <input> ref 关联到
// 构造器里创建的 `textInput` 上
return (
<div>
<input
type="text"
ref={this.textInput} />
<input
type="button"
value="Focus the text input"
onClick={this.focusTextInput}
/>
</div>
);
}
}
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
}
}
render() {
return (
<div>
<AutoFocusTextInput></AutoFocusTextInput>
</div>
)
}
}
let root = ReactDOM.createRoot(document.getElementById('root'))
root.render(<App></App>)
本文标题:ref
本文链接:https://www.haomeiwen.com/subject/wexkirtx.html
网友评论