前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >[OHIF-Viewers]医疗数字阅片-医学影像-获取焦点的2种方式-ref

[OHIF-Viewers]医疗数字阅片-医学影像-获取焦点的2种方式-ref

作者头像
landv
发布2020-07-13 14:23:25
5280
发布2020-07-13 14:23:25
举报
文章被收录于专栏:landvlandv

[OHIF-Viewers]医疗数字阅片-医学影像-获取焦点的2种方式-ref

前言 在React中,只要props或state发生改变,则render()方法必定执行,即DOM会更新。然React更新DOM时,可能会导致已经获取焦点的元素失去焦点,故此时需要操作DOM,获取焦点。

方式一:

React.createRef() 使用React.createRef()方法可以创建一个存储dom的ref,当ref设置在组件上时,即可存储该元素的dom引用。

代码语言:javascript
复制
// index.js
import React from 'react'
import CustomTextInput from './CustomTextInput'

class Parent extends React.Component {
  constructor(props) {
    super(props);
    // 创建一个ref存储dom元素
    this.inputElement = React.createRef();
    this.getFocus = this.getFocus.bind(this)
  }

  getFocus() {
    this.inputElement.current.focus()
  }

  render() {
    return (
      <CustomTextInput
        inputRef={this.inputElement}
        inputGetFocus={this.getFocus}
      />
    )
  }
}

export default Parent
代码语言:javascript
复制
// CustomTextInput.js
import React from 'react'

const CustomTextInput = (props) => {
  return (
    <React.Fragment>
      <input
        type="text"
        ref={props.inputRef}
      />
      <button onClick={props.inputGetFocus}>获取焦点</button>
    </React.Fragment>
  )
}

export default CustomTextInput

方式二:使用函数

代码语言:javascript
复制
// index.js
import React from 'react'
import CustomTextInput from './CustomTextInput'

class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.getInputElement = this.getInputElement.bind(this)
    this.getFocus = this.getFocus.bind(this)
  }

  getFocus() {
    this.inputElement.focus()
  }

  getInputElement(el) {
    this.inputElement = el
  }

  render() {
    return (
      <CustomTextInput
        inputRef={this.getInputElement}
        inputGetFocus={this.getFocus}
      />
    )
  }
}

export default Parent

 OHIF是酱紫实现的:

代码语言:javascript
复制
    <div className="ViewportDownloadForm" >
      <div
        style={{
          height: viewportElementDimensions.height,
          width: viewportElementDimensions.width,
          position: 'absolute',
          left: '9999px',
        }}
        ref={ref => setViewportElement(ref)}
      >
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-07-09 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • [OHIF-Viewers]医疗数字阅片-医学影像-获取焦点的2种方式-ref
    • 方式一:
      • 方式二:使用函数
        •  OHIF是酱紫实现的:
        相关产品与服务
        对象存储
        对象存储(Cloud Object Storage,COS)是由腾讯云推出的无目录层次结构、无数据格式限制,可容纳海量数据且支持 HTTP/HTTPS 协议访问的分布式存储服务。腾讯云 COS 的存储桶空间无容量上限,无需分区管理,适用于 CDN 数据分发、数据万象处理或大数据计算与分析的数据湖等多种场景。
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档