2.4 组件实例的三大核心属性3:refs与事件处理
-
效果
-
理解
组件内的标签可以定义ref属性来标识自己
-
编码
-
字符串形式的ref
<input ref="input1" />
-
回调形式的ref
<input ref={(c)=>{this.input1 = c}} />
如果ref回调函数是以内联函数的方式定义的,在更新过程中它会被执行两次,第一次传入参数null, 然后第二次会传入DOM元素。这是一位内在每次渲染时会创建一个新的函数实例,所以React清空旧的ref并且设置新的。通过将ref的回调函数定义成class的绑定函数的方式可以避免上述问题,但大多情况下无关紧要。
// 创建组件 class Demo extends React.Component{ state = {isHot:true}; showData = ()=>{ console.log(this.refs.input1.value); } changeWeather = ()=>{ // 获取原来的状态 const {isHot} = this.state; // 更新状态 this.setState({isHot : !isHot}) } saveInput = (c)=>{ this.input1 = c; console.log('@', c); } render(){ const {isHot} = this.state; return ( <div> <h2>今天天气很{isHot?'炎热':'凉爽'}</h2> {/* <input ref={(c)=>{this.input1 = c; console.log('@',c);}} type="text" placeholder="点击按钮提示数据" /> */} {/* 内绑定 */} <input ref={this.saveInput} type="text" placeholder="点击按钮提示数据" /> <button ref="button123" onClick={this.showData}>点我提示数据</button> <button onClick={this.changeWeather}>点我切换天气</button> </div> ) }} // 渲染组件到页面 ReactDOM.render(<Demo/>, document.getElementById('container'))
- createRef创建ref容器
myRef = React.createRef(); <input ref={this.myRef} />
// 创建组件 class Demo extends React.Component{ /* React.createRef 调用后可以返回一个容器,该容器可以存储被ref所标识的节点 专人专用!!! */ myRef = React.createRef(); showData = ()=>{ alert(this.myRef.current.value); console.log(this.myRef.current); } render(){ return ( <div> <input ref={this.myRef} type="text" placeholder="点击按钮提示数据" /> <button ref="button123" onClick={this.showData}>点我提示数据</button> </div> ) } } // 渲染组件到页面 ReactDOM.render(<Demo/>, document.getElementById('container'))
-
-
react 中的事件处理
通过onXxx属性指定事件处理函数
- React使用的是自定义事件,而不是原生的DOM事件
- React中的事件试通过事件委托方式处理的(委托给组件最外层的元素)
通过
event.target
得到发生时间的DOM元素对象 —— 不要过度使用refs