React 三大组件核心属性之 refs 与时间处理
React 三大组件核心属性之 refs 与事件处理
- 需求:
- 两个输入框中间又一个按钮
- 点击按钮提示左侧输入框数据
- 右侧输入框失去焦点提示数据
字符串形式的 ref
- 在元素中添加 ref 属性会添加到组件实例的 refs 中
class MyComponent extends React.Component {
// 展示左侧输入框的数据
showData = () => {
const { input } = this.refs;
alert(input.value)
}
// 展示右侧输入框的数据
showData2 = () => {
const { input2 } = this.refs;
alert(input2.value)
}
render() {
return (
<div>
<input ref="input" type="text" placeholder="点击按钮提示数据" />
<button onClick={this.showData}>点击提示左侧的数据</button>
<input ref="input2" onBlur={this.showData2} type="text" placeholder="失去焦点提示数据" />
</div>
)
}
}
- 过时的 api
- 可能在未来版本废除
- 效率不好
会调函数形式的 ref
- 在 ref 中写一个回调函数,react 会帮你调用
- 回调函数的参数就是元素节点
- 将元素节点赋在组件实例上
class MyComponent extends React.Component {
// 展示左侧输入框的数据
showData = () => {
const { input } = this;
alert(input.value)
}
// 展示右侧输入框的数据
showData2 = () => {
const { input2 } = this;
alert(input2.value)
}
render() {
return (
<div>
<input ref={c => this.input = c} type="text" placeholder="点击按钮提示数据" />
<button onClick={this.showData}>点击提示左侧的数据</button>
<input ref={c => this.input2 = c} onBlur={this.showData2} type="text" placeholder="失去焦点提示数据" />
</div>
)
}
}
createRef
- React.createRef 调用后可以返回一个容器,该容器可以存储被 ref 所标示的节点
class MyComponent extends React.Component {
myRef = React.createRef();
myRef2 = React.createRef();
// 展示左侧输入框的数据
showData = () => {
const { current } = this.myRef;
alert(current.value)
}
// 展示右侧输入框的数据
showData2 = () => {
const { current } = this.myRef2;
alert(current.value)
}
render() {
return (
<div>
<input ref={this.myRef} type="text" placeholder="点击按钮提示数据" />
<button onClick={this.showData}>点击提示左侧的数据</button>
<input ref={this.myRef2} onBlur={this.showData2} type="text" placeholder="失去焦点提示数据" />
</div>
)
}
}
- 官方最推荐写法
事件处理
- 通过 onXxx 属性指定事件处理函数 (注意大小写)
- 兼容性:React 使用的是自定义(合成)事件,而不是使用的原生的 DOM 事件
- 高效:React 中的事件是通过事件委托方式处理的(委托给组件最外层的元素)
- 通过 event.target 得到发生事件的 DOM 元素对象
- 发生事件的元素正好是你操作的元素,可以用 event.target 代替 ref
- 不要过度的使用 ref
class MyComponent extends React.Component {
myRef = React.createRef();
// 展示左侧输入框的数据
showData = () => {
const { current } = this.myRef;
alert(current.value)
}
// 展示右侧输入框的数据
showData2 = (event) => {
alert(event.target.value)
}
render() {
return (
<div>
<input ref={this.myRef} type="text" placeholder="点击按钮提示数据" />
<button onClick={this.showData}>点击提示左侧的数据</button>
<input onBlur={this.showData2} type="text" placeholder="失去焦点提示数据" />
</div>
)
}
}
本文来自博客园,作者:懒惰ing,转载请注明原文链接:https://www.cnblogs.com/landuo629/p/14970084.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?