大家好,很高兴又见面了,我是"高级前端进阶",由我带着大家一起关注前端前沿、深入前端底层技术,大家一起进步,也欢迎大家关注、点赞、收藏、转发,您的支持是我不断创作的动力。
![](http://image.uc.cn/s/wemedia/s/upload/2024/7629f1830d82de6dfbeb8b3e859360e8.png)
react-archer 用于在 React 中的 DOM 元素之间绘制箭头,让组件之间关系更加清晰。
![](http://image.uc.cn/s/wemedia/s/upload/2024/5ec0f602c30487ee63ce333e767cd506.png)
![](http://image.uc.cn/s/wemedia/s/upload/2024/6c442cdae6c1e73dc9fc6cb94eb660ed.png)
目前 react-archer 在 Github 通过 MIT 协议开源,有超过 1.2k 的 star,是一个有意思的前端开源项目。
如何使用 react-archerimport {ArcherContainer, ArcherElement} from 'react-archer';const rootStyle = {display: 'flex', justifyContent: 'center'};const rowStyle = {margin: '200px 0', display: 'flex', justifyContent: 'space-between'};const boxStyle = {padding: '10px', border: '1px solid black'};const App = () => { return ( <div style={{ height: '500px', margin: '50px'}}> <ArcherContainer strokeColor="red"> <div style={rootStyle}> <ArcherElement id="root" // 标识 ArcherElement 的 id relations={[ { targetId: 'element2', targetAnchor: 'top', sourceAnchor: 'bottom', style: {strokeDasharray: '5,5'}, }, ]} > <div style={boxStyle}>Root</div> </ArcherElement> </div> <div style={rowStyle}> <ArcherElement id="element2" relations={[ { targetId: 'element3', targetAnchor: 'left', sourceAnchor: 'right', style: {strokeColor: 'blue', strokeWidth: 1}, label: <div style={{ marginTop: '-20px'}}>Arrow 2</div>, }, ]} > <div style={boxStyle}>Element 2</div> </ArcherElement> <ArcherElement id="element3"> <div style={boxStyle}>Element 3</div> </ArcherElement> <ArcherElement id="element4" relations={[ { targetId: 'root', targetAnchor: 'right', sourceAnchor: 'left', label: 'Arrow 3', }, ]} > <div style={boxStyle}>Element 4</div> </ArcherElement> </div> </ArcherContainer> </div> );};export default App;需要注意的是,ArcherElement 的 children 必须是单个元素或内部上下文函数。如果传递自定义组件,则应将其包装在 div 中,或者使用引用转发(forward the reference)。
如果访问 ArcherContainer 的 ref,将可以访问 refreshScreen 方法,该方法可以让开发者更好地控制何时重新绘制箭头。
参考资料https://dev.to/trevortx/react-archer-drawing-arrows-between-dom-elements-co
https://github.com/pierpo/react-archer