没有和state数据源进行关联的表单项,而是借助ref,使用元素DOM方式获取表单元素值
使用步骤
- 调用 React.createRef() 方法创建ref对象
- 将创建好的 ref 对象添加到文本框中
- 通过ref对象获取到文本框的值
class App extends React.Component {
constructor(props){
super(props)
//创建 ref
this.username = React.createRef()
}
// 获取文本框的值
fn =() => {
console.log(this.username.current.value)
}
render(){
return (
<div>
<input type ="text" ref={this.username} />
<button onClick ={this.fn}>获取值</button>
</div>
)
}
import React, { Component, createRef } from 'react'
// import React, { Component } from 'react'
export default class User3 extends Component {
// 构造方法
constructor(props) {
super(props);
// 定义一个用户的引用
this.username = createRef()
}
addUser() {
console.log(this.username.current.value);
}
render() {
return (
<div>
<div>
{/* 非受控组件 */}
<input type="text" ref={this.username} />
</div>
<div>
<button onClick={this.addUser.bind(this)}>添加用户</button>
</div>
</div>
)
}
}
