react 官方给我提供了一个 ref 把想要获取的div的dom绑定上 ref{this.name} this.名字是自己取得。下面是代码:
import React from 'react'
export default class form_input extends React.Component{
constructor(){
super()
// 获取DOM节点
this.dom = React.createRef();
this.usname = React.createRef()
this.age = React.createRef()
}
// 获取DOM节点
componentDidMount(){
this.dom.current.style.color = 'red'
}
// 获取input DOM节点
sbmmt(){
console.log(this.usname.current.value)
console.log(this.usname.current.value)
}
render(){
return(
<div>
<hr/>
{/* 获取DOM节点 */}
<h1 ref={this.dom}>表单组件</h1>
{/*获取input dom 节点 */}
<input type="text" ref={this.usname}></input>
<input type="text" ref={this.age}></input>
<button onClick={this.sbmmt.bind(this)}>提交信息</button>
</div>
)
}
}
改变的颜色和输入的值现在都能获取的到