zoukankan      html  css  js  c++  java
  • [OHIF-Viewers]医疗数字阅片-医学影像-获取焦点的2种方式-ref

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

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

    方式一:

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

    // 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
    // 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

    方式二:使用函数

    // 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是酱紫实现的:

        <div className="ViewportDownloadForm" >
          <div
            style={{
              height: viewportElementDimensions.height,
               viewportElementDimensions.width,
              position: 'absolute',
              left: '9999px',
            }}
            ref={ref => setViewportElement(ref)}
          >
  • 相关阅读:
    rgba()和opacity的比较(转)
    CSS定位以及z-index属性(层叠性)的详解(转)
    hadoop 集群HA高可用搭建以及问题解决方案
    服务容错模式
    分布式系统基础总结
    当Kubernets遇上阿里云 -之七层负载均衡(一).
    HAProxy负载均衡原理及企业级实例部署haproxy集群
    基于Docker Compose构建的MySQL MHA集群
    使用 Mesos 管理虚拟机
    VMware VSAN 入门与配置(一)
  • 原文地址:https://www.cnblogs.com/landv/p/13273468.html
Copyright © 2011-2022 走看看