获取input输入框中的值(分为两种情况):
1. 仅获取input输入框的值,该input不存在事件发生
handleClick() {
// const input = this.refs.content
// alert(input.value)
const input = this.input.value
alert(input)
}
2. 获取存在事件发生的input元素的值(利用形参event)
handleBlur(event) {
const input2 = event.target.value
alert(input2)
}
所有代码:
import React from 'react';
class Add extends React.Component {
constructor(props) {
super(props);
this.state = {}
this.handleClick = this.handleClick.bind(this)
}
handleClick() {
// const input = this.refs.content
// alert(input.value)
const input = this.input.value
alert(input)
}
handleBlur(event) {
const input2 = event.target.value
alert(input2)
}
render() {
return (
<div>
{/* <input type="text" ref="content"/> */}
<input type="text" ref={input => this.input = input}/> {/*推荐*/}
<button onClick={this.handleClick}>提示输入内容</button>
<input type="text" placeholder="失去焦点后提示内容" onBlur={this.handleBlur}/>
</div>
);
}
}
export default Add;
可能疑问点:在获取存在事件发生的input元素的值时,没有用到this,还需要在constructor中将新增函数中的this强行绑定为组件对象嘛?
并且本人在没有绑定的情况下,也可以获取到input元素的值。但是,handleBlur方法中的this为undefined。
大家在看到我的代码之后,也就看到了我没有在constructor中给handleBlur方法中的this强行绑定,原因是我在实现这一功能时没有用到this,但是若后边在该方法中使用到this的话,必须要进行绑定。