react引用
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root'));
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myInput = React.createRef();
}
handleClick() {
// 使用原生的 DOM API 获取焦点
this.myInput.current.focus();
var v = this.myInput.current.value;
console.log(v);
}
render() {
// 当组件插入到 DOM 后,ref 属性添加一个组件的引用于到 this.refs
return (
<div>
<input type="text" ref={this.myInput} />
<input
type="button"
value="点我输入框获取焦点"
onClick={this.handleClick.bind(this)}
/>
</div>
);
}
}
root.render(
<div>
<MyComponent />,
</div>
);
评论已关闭