需求:
自定义组件,功能说明如下:1.点击按钮,提示第一个输入框中的值 2.当第2个输入框失去焦点时,提示这个输入框中的值。
不用你res的写法:
class Demo extends React.Component {
showData = ()=>{
const input = document.getElementById(‘input1’);
alert(input.value);
}
render() {
return (
点我提示左侧数据
)
}
}
ReactDOM.render(,document.getElementById(‘test’))
使用ref:
点我提示左侧数据
showData = ()=>{ console.log(this) }  可见 标签上如果有ref 就会放入当前组件实例中的refs中 ref的值为key 被写ref的标签的真是DOM作为值。 所以: 左边的的输入框的值应该这么取出来:this.refs.input1.value失去焦点的做法也一样:
showData2 = ()=>{
const{input2} = this.refs
alert(input2.value)
}
<input ref="input2" onBlur={this.showData2} type="text" placeholder="失去焦点提示数据"/>
完整源码:
<script type="text/babel"> //此处一定要写babel 表示该标签中写入jsx语法并且使用babel转为js语法
class Demo extends React.Component {
// showData = ()=>{
// const input = document.getElementById('input1');
// alert(input.value);
// }
showData = ()=>{
const{input1} = this.refs
alert(input1.value)
}
showData2 = ()=>{
const{input2} = this.refs
alert(input2.value)
}
render() {
return (
<div>
<input ref="input1" type="text" placeholder="点击按钮提示数据"/>
<button onClick={this.showData}>点我提示左侧数据</button>
<input ref="input2" onBlur={this.showData2} type="text" placeholder="失去焦点提示数据"/>
</div>
)
}
}
ReactDOM.render(<Demo/>,document.getElementById('test'))
</script>