【问题标题】:The rendering order of the React-raphael components (like z-index)React-raphael 组件的渲染顺序(如 z-index)
【发布时间】:2021-01-09 21:06:22
【问题描述】:

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

这是一个简化的视图:

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

【问题讨论】:

  • svg 中的 Z-index 只是添加元素的顺序。如果您想将一个元素移到另一个元素的前面,只需将其删除并读入树的后面部分即可。

标签: reactjs raphael


【解决方案1】:

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, 0, 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> 
  )
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-30
    • 2021-02-18
    • 1970-01-01
    • 2010-10-15
    • 1970-01-01
    • 2011-09-27
    • 2021-05-11
    相关资源
    最近更新 更多