首页 > 解决方案 > 将 foreignObject 定位到 svg 的右上角

问题描述

我正在向foreignObject基于svg. 我想把它放在右上角svg,不管它有多大/小svg。所以我不想要一个硬编码的解决方案,我需要一个动态的解决方案。

width={'100%'} height={'100%'}在 中设置foreignObject是不可行的,因为它会使图表的其余部分无法点击。

我通过在里面手动设置x和手动获得了一个非动态解决方案,但我需要一个动态解决方案。yforeignObject

我怎样才能做到这一点?

在此处输入图像描述

<g>
    <foreignObject //x={0} y={0} 
    width={'1'} height={'1'} style={{overflow: 'visible'}} x={50} y={50}>
     <Menu>
        <MenuButton as={Button} rightIcon={<ChevronDownIcon />}         
        transition="all 0.001s"
        borderRadius="md"
        borderWidth="0px"
        _hover={{ bg: "gray.400" }}
        _expanded={{ bg: "blue.400" }}
        _focus={{ boxShadow: "none" }}
        style={{ marginTop: "1px", position: "absolute", right: 0 }}>
          Actions
        </MenuButton>
        <Portal>
        <MenuList zIndex={10}>
          <MenuItem>Download</MenuItem>
          <MenuItem>Create a Copy</MenuItem>
          <MenuItem>Mark as Draft</MenuItem>
          <MenuItem>Delete</MenuItem>
          <MenuItem>Attend a Workshop</MenuItem>
        </MenuList>
        </Portal>
      </Menu>
    </foreignObject>
</g>

代码沙盒:

https://codesandbox.io/s/floral-water-v11gx?file=/src/BasicLineSeries.tsx

标签: javascriptreactjssvgforeignobject

解决方案


您的父组件BasicLineSeries已经知道width,因此您可以将其传递给生成的组件foreignObject,如下所示:

       <ChartCanvas
          height={height}
          ratio={ratio}
          width={width}
          ...
        >
          <Chart id={1} yExtents={this.yExtents}>
            <LineSeries yAccessor={this.yAccessor} strokeWidth={3} />
            <XAxis />
            <YAxis />
          </Chart>
          <TestMenu width={width} />
        </ChartCanvas>
function TestMenu({width}) {
  return (
    <g className="react-financial-charts-enable-interaction">
      <foreignObject
        width={"1"}
        height={"1"}
        style={{ overflow: "visible" }}
        x={width}
        y={50}
      >

推荐阅读