在项目开发过程中难免会操作dom,react废弃了this.refs,ref引用的写法有了改变。
使用React.createRef()后,通过ref的current属性将能得到dom节点或组件的实例
//绑定ref
<input ref="getInput"/>
//获取dom元素的值
console.log(this.refs.getInput.state.value)
export default class Header extends Component {
constructor(props){
super(props)
this.todoInput = React.createRef()
}
handleEnter = (event) => {
//即可获取dom的值
console.log(this.todoInput.current.state.value)
}
render() {
return (
<div className="header">
<Input placeholder="回车确认" ref={this.todoInput} onPressEnter={this.handleEnter}/>
</div>
)
}
}
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.bodyBox = React.createRef();
}
getDom () {
const bodyBoxDom = this.bodyBox && this.bodyBox.current
Console.log (bodyBoxDom)
}
render() {
return <div ref={this.bodyBox} onClick={this.getDom}/>
}
}