简体   繁体   English

React:根据屏幕位置更改元素类

[英]React: change element class depending on screen position

I have a React component.我有一个 React 组件。 Which renders a row of images.渲染一行图像。 On mouse over a bigger preview if the picture is displayed on the left hand side of the picture.如果图片显示在图片的左侧,则将鼠标悬停在更大的预览上。 However now I would like to put the preview on the right hand side if the original picture is on the left part of the window.但是现在如果原始图片在窗口的左侧,我想将预览放在右侧。 My current implemention is very slow.我目前的实施很慢。

import React from 'react';
import { calculateDimensions, calculateTimeDifference, postData } from '../Tools';
import { CONST } from '../config';

export class Picture extends React.Component {

    constructor(props) {
    super(props);
    this.state = {
      bookmark: this.props.picture.bookmark,
      stars: parseInt(this.props.picture.stars),
      showPreview: false,
    };

    this.url = CONST.URL_RESTSERVICE + '/picture/update.php';
  }

  componentDidMount() {
    this.setPictureClass();
  }

  componentDidUpdate() {
    this.setPictureClass();
  }

  setPictureClass() {
    // set class to all pictues so they wil get alignet properly
    let pic = document.getElementById('pic' + this.props.picture.id);
      const offsetLeft = pic.getBoundingClientRect().left;
      const width  = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
      pic.classList.remove("tooltipPicRight");
      pic.classList.remove("tooltipPicLeft");
      if (width / 2 < offsetLeft ) {
        pic.classList.add("tooltipPicRight");
      } else {
        pic.classList.add("tooltipPicLeft");
      }
  }

  render() {
    const pic = this.props.picture;
    const stars = parseInt(this.state.stars);
    calculateDimensions(pic);
    let timeDiffernce = null;
    if (pic.date && pic.previousDate) {
      timeDiffernce = calculateTimeDifference(pic.date, pic.previousDate);
    }

    // const inputRef = useRef();

    return (
    <div className="inline-block align-center picture">
      <div className="block tooltipPic" id={'pic' + pic.id}>
        {
        this.props.handleClickPicturePreview ?
        <img onClick={() => this.props.handleClickPicturePreview(pic)} src={pic.picLocation} width={pic.width ? calculateDimensions(pic).width : 0} height={pic.height ? calculateDimensions(pic).height : 0} loading="lazy" alt={pic.id} />
        : <a href={pic.picLocation} target="_blank" rel="noopener noreferrer"><img src={pic.picLocation} width={pic.width ? calculateDimensions(pic).width : 0} height={pic.height ? calculateDimensions(pic).height : 0} loading="lazy" alt={pic.id} className=""/></a>
        }
        <span className="tooltiptextPic"><img src={pic.picLocation} width={pic.width ? calculateDimensions(pic, 600, 600).width : 0} height={pic.height ? calculateDimensions(pic, 600, 600).height : 0} loading="lazy" alt={pic.id} /></span>
      </div>
    </div>);
  }
}

you can use element.getBoundingClientRect() which will let you know where in the screes is the image (or element) is appearing, so you can set an if, if it's too close of the left edge, then send it to the other side: https://gomakethings.com/how-to-test-if-an-element-is-in-the-viewport-with-vanilla-javascript/您可以使用element.getBoundingClientRect()它将让您知道图像(或元素)出现在屏幕中的哪个位置,因此您可以设置一个 if,如果它离左边缘太近,则将其发送到另一侧: https://gomakethings.com/how-to-test-if-an-element-is-in-the-viewport-with-vanilla-javascript/

What I would do is to create a css class that pushes the image where I want it to appear,我要做的是创建一个 css 类,将图像推送到我希望它出现的位置,

   .push-image{
    // Some style
    margin-left: 99px; //Whathever you need
    }

Then calculate the position where the image will be rendered然后计算图像将被渲染的位置

componentDidMount(){
// Find the element already rendered
const divToCheck =  document.getElementById({'pic' + pic.id});

// Get the position
let bounding = divToCheck.getBoundingClientRect();

// Log the results
console.log(bounding);
// {
//  height: 118,
//  width: 591.359375,
//  top: 137,
//  bottom: 255,
//  left: 40.3125,
//  right: 631.671875
// }

// set state so the render has access
this.setState({
boundingPositionX: bounding.left,
})

}

Finally dinamically set the class最后动态设置类

render(){
let classToPush;
this.state.boundingPositionX < 99 ? classToPush = "push-image" : classToPush = "";
}

If everything goes right, you should be able to push the element to the right如果一切顺利,您应该能够将元素向右推

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 React 应用程序中屏幕垂直中心的 Position 元素 - Position element in the vertical centre of the screen in a React application 根据 React 中的组件状态更改 Bootstrap 类 - Change Bootstrap class depending of component state in React React:如何根据路线更改页脚组件的位置 - React: How to change position of footer component depending on route React Element更改类onClick - React Element change class onClick 如何在屏幕底部 position 一个 React Native 元素? - How can I position a React Native element at the bottom of the screen? <a>在react-bootstrap NavItem中</a>更改<a>元素类</a> - Change the <a> element class in react-bootstrap NavItem 如何在反应(顺风)中动态更改元素的 position? - How do I dynamically change the position of an element in react (tailwind)? 反应数组改变 object 元素的 position 的 setState (useState hook) - React setState (useState hook) of array change position of object element React - 根据自己的 position 有条件地更改元素的样式 - React - Conditionally change the style of an element based on its own position 根据屏幕宽度在 UI 中使用 React 更改元素行为 - Using React change element behavior in UI based on screen width
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM