我有一个可重用的React列表组件,它可以有嵌套的子节点,我想从父节点画一个箭头到所有直接的子节点,就像下图一样。
下面是一个嵌套列表组件的例子。
import React from 'react';
import ListElement from './ListElement.js';
const List = () => (
<>
<ListElement>
<ListElement>
<ListElement>
<ListElement />
<ListElement>
<ListElement />
</ListElement>
</ListElement>
<ListElement />
</ListElement>
<ListElement />
</ListElement>
<ListElement />
</>
);
export default List;
ListElement组件看起来像这样
import React from 'react';
const ListElement = props => {
const indentationStyle = { paddingLeft: `${3 * props.indent}rem`,
position: 'relative'};
const lineStyle = {
left: `${2 + 3 * (props.indent - 1.2)}rem`,
};
const tile = (
<div style={indentationStyle}>
{props.indent > 0 ? (
<div className={'arrow-line-container'} style={lineStyle}>
<div className={'arrow-line'}/>
<div className={'curve-arrow-line'}/>
</div>
) : null}
<div
style={{
border: '1px solid black',
padding: '1rem',
marginBottom: '1rem',
}}
>
I am a ListElement
</div>
</div>
);
const getChildren = () => {
let elements = React.Children.toArray(props.children);
// increase indent prop of each child and assign what number child it is in the list
elements = elements.map((element, index) => {
return React.cloneElement(element, {
...element.props,
indent: props.indent + 1,
childNumber: index,
});
});
return elements;
};
const childTiles = <div className={'child-tile'}>{getChildren()}</div>;
const arrowStyle = {
backgroundPosition: `${1.3 + 3 * (props.indent - 1)}rem`,
};
return (
<>
<ul className={'no-bullet'}>
<li
className={props.indent === 0 ? 'no-arrow' : 'arrow'}
style={arrowStyle}
>
{tile}
</li>
{props.children ? childTiles : null}
</ul>
</>
);
};
ListElement.defaultProps = {
childNumber: 0,
indent: 0,
};
export default ListElement;
css看起来是这样的
ul.no-bullet {
list-style-type: none;
padding: 0;
margin: 0;
}
.arrow-line {
border-left: 2px solid #6a6969;
content: "";
position: absolute;
height: 65%;
}
li.arrow {
background: url("./arrow.png") no-repeat;
}
li.no-arrow {
display: block;
}
目前,我在创建列表时使用了 <li>
元素,并将子弹改为箭头的图像。我想从父元素中绘制线条,并将其附加到每个子元素的箭头上。我正在努力计算线条的正确高度和线条顶部的位置。任何建议都是感激的。
这里有一个Plunker的链接。https:/plnkr.coeditGFrriWfJyeur7MRh?open=Hello.js&deferRun=1&preview。
我设法找到了一个解决方案,只画一条线在最后一个孩子和使用 offsetTop
和 getBoundingClientRect().height
来计算箭线的位置和高度。工作解决方案在这里。https:/plnkr.coeditSFzgiZi1dckRa79C。