import React
, { Component
} from 'react'
class RefsDemo extends Component {
constructor(props
) {
super(props
)
this.inputRef
= React
.createRef()
this.cbRef
= null
this.setCbRef = (element
) => {
this.cbRef
= element
}
}
componentDidMount() {
if(this.cbDef
) {
this.cbRef
.focus()
}
}
clickHandler = () => {
alert(this.inputRef
.current
.value
)
}
render() {
return (
<div
>
<input type
="text" ref
={this.inputRef
}/>
<input type
="text" ref
={this.setCbRef
}/>
<button onClick
={this.clickHandler
}>Click
</button
>
</div
>
)
}
}
export default RefsDemo
在App.js 文件中
import React
from 'react';
import './App.css';
import RefsDemo
from './RefsDemo';
function App() {
return (
<div className
="App">
<RefsDemo
/>
</div
>
);
}
export default App
;
结果如下:
当我在第一个方框里输入"world"时,点击Click按钮,就会弹出Alert框
如果觉得不错的话,就用点赞来代替五星好评吧!
转载请注明原文地址:https://ipadbbs.8miu.com/read-65445.html