两种方法现在均可使用找一个可以正常运行的组件放入,查看效果
1.实例方法 需要再构造方法中提前创建节点
2.函数传参方法(个人觉得第二种方法简单些)
代码如下:
class Search extends Component {
constructor (props) {
super(props)
// 第一种方法用到的引用创建
this.keyWordElementNew = React.createRef()
}
search = () => {
//第一种放获取到的结果
console.log(this.keyWordElementNew.current.value)
// 第二种方法获取到的结果
console.log(this.keyWordElement.value)
}
render () {
return (
<div className='search'>
<input ref={this.keyWordElementNew} type='text' placeholder='第一种通过ref获取input值的方法'/>
<input ref={c => this.keyWordElement = c} placeholder='第二种通过ref获取input值的方法'/>
<button onClick={this.search}>搜索</button>
</div>
)
}
}