React+Leaflet.js中如何为GeoJSON对象设置条件化背景图案?
如何在React-Leaflet的GeoJSON组件中设置带图案的填充背景?
我有一个React应用,使用如下组件绘制地图:
const MyGeoJsonComponent: React.FC<GeoJSONProps> = (props) => { ... return ( <GeoJSON ref={geoRef} key={Math.random()} data={feature} style={getStyle} onEachFeature={onEachFeature} {...feature} > ... </GeoJSON> );};
目前我通过style={}属性为每个GeoJSON对象上色,但希望根据特定条件为其设置带图案(如条纹)的背景。尝试给fillColor属性设置任何"background:"属性时,所有GeoJSON对象都会默认显示灰色背景。请问是否可以通过Leaflet.js或其他第三方库实现该需求?
可行解决方案
我找到了一个有效的实现方式,借助styled-components库创建全局样式,通过条件选择器为目标GeoJSON对象设置渐变条纹背景:
const GlobalStyle = createGlobalStyle<{ $color?: string; $customProp?: string }>` [customAttr='${({ $customProp }) => $customProp}'] { background: repeating-linear-gradient( 45deg, ${({ $color }) => $color}33, ${({ $color }) => $color}33 10px, ${({ $color }) => $color}CC 5px, ${({ $color }) => $color}CC 15px ); } `;
随后在渲染组件时,根据特定条件引入这个全局样式即可:
{ someCondition && ( <GlobalStyle $color={properties.color} $customProp={properties.customProp} /> )}
希望能帮助到有需要的人。
内容的提问来源于stack exchange,提问作者valio_sg
相关产品推荐
相关产品推荐

