微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

React-raphael 组件的渲染顺序如 z-index

如何解决React-raphael 组件的渲染顺序如 z-index

我希望按照我需要的顺序绘制 Raphael-react 组件(创建不同的层或类似 z-index 的东西)。如何控制组件“Path”在“Paper”上的位置?

这是一个简化的视图:

<Paper>
 <Set>
   <Path .../>
   <Path .../>
   <Path .../>
 </Set>             
</Paper>

解决方法

Raphael 似乎不支持 z-index,但是如果将所有数据保存在 local state(或 Redux)中的数组中,则可以实现目标:

  const [data,setData] = useState([
    { x: 50,y: 50,r: 40,attr: { stroke: "#0b8ac9","stroke-width": 5 }},... 
  ])

然后,如果您想更改元素的 z-Index,只需将其移动到数组中即可:

  zIndexOrder = [ ...,-1,1,...] // last element has big z-index

我为你准备了奥运五环的演示,我只是在那里洗牌。

  const randomizeZIndex = () => {
    const temp = [...data];
    temp.sort(() => Math.random() - 0.5);
    setData(temp);
  };

你可以看到它here

当然,random 是没有用的。您需要在每个元素上维护一个 zOrder 才能正常工作。

如果您想处理所有数字,您可以添加 polymorphism。并保存元素的类型(圆、线等)

const elements = [{
  type: "Rect",key: "FirstRect",zOrder: 0,options: {
     x:30,y:148,width:240,height:150,attr:{"fill":"#10a54a","stroke":"#f0c620","stroke-width":5
   }
 }},...];

代码如下:

import React,{Fragment} from 'react';
import { Raphael,Paper,Set,Rect,Line } from "react-raphael";

const RaphaelElement = {
  Line: function line({options}) {
    return <Line {...options}/>; // react-raphael Line
  },Rect: function rect({options}) {
    return <Rect {...options}/>; // react-raphael Rect
  }
}

const AllElements = ({elements}) => {
  return (
     <Fragment>
      { // with polymorphism
        elements.map(({options,key,type}) => {
          const CurrRaphaelElement = RaphaelElement[type];
          return <CurrRaphaelElement key={key} options={options} />
        })
      }
     </Fragment> 
  )
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。