将属性添加到 React 中地图的路径 svg 组件
Add attributes to a path svg component for a map in React
我正在尝试实现一个使用我创建的 svg 地图的策略游戏,我想在每个“路径”(这将是领土)和一些其他道具中添加一些属性,如“部队”。是否可以仅将 att(props) 添加到路径,然后在作为整个地图的 svg 标签内使用此组件。所以基本上我想知道如何使用 att(props) 和地图中的输入或标签创建领土对象,以便稍后我可以添加 onClick 事件和其他事件。
目前我有 Map 组件和 Territory 组件(我不确定这是否是处理它的最佳方式。)
const Territory = ({ tD }) => {
const [color, setColor] = useState('red')
const [troops, setTroops] = useState(21)
return (
<>
<input type="text" />
<path fill-rule="evenodd" clip-rule="evenodd" d={tD} fill={color} stroke="black" />
</>
);
};
export default Territory;
const Map = () => {
return (
<svg width="1397" height="686" viewBox="0 0 1397 686" fill="none" xmlns="http://www.w3.org/2000/svg">
{territories.map(territory => (
<Territory key={territory.id} tD={territory.tD} />
))}
</svg>
);
};
我想在每个领土的地图输入或标签中添加可见的部队(数字)。像这样的
map with inputs
可以吗?构建具有“部队”等道具的领土组件的最佳方法是什么
非常感谢帮助我的人。
您将 HTML <input />
正常渲染为 svg
的一部分,这不起作用。如果任何东西不是 svg
的一部分,并且您将其渲染为 svg
的子级,那么您必须将其包装为 foreignObject.
区域组件
const Territory = ({ tD }) => {
const [color, setColor] = useState('red')
const [troops, setTroops] = useState(21)
return (
<g>
<foreignObject x="40" y="40" width="100" height="100">
<div xmlns="http://www.w3.org/1999/xhtml">
<input type="text" />
</div>
</foreignObject>
<path fill-rule="evenodd" clip-rule="evenodd" d={tD} fill={color} stroke="black" />
</g>
);
};
注:
- 不要忘记
height
和 width
属性。您可能还需要 x
& y
。
- 不要忘记容器 HTML 元素上的
xmlns="http://www.w3.org/1999/xhtml"
。
- 您可以使用
svg <g />
标签对元素进行分组。
我正在尝试实现一个使用我创建的 svg 地图的策略游戏,我想在每个“路径”(这将是领土)和一些其他道具中添加一些属性,如“部队”。是否可以仅将 att(props) 添加到路径,然后在作为整个地图的 svg 标签内使用此组件。所以基本上我想知道如何使用 att(props) 和地图中的输入或标签创建领土对象,以便稍后我可以添加 onClick 事件和其他事件。
目前我有 Map 组件和 Territory 组件(我不确定这是否是处理它的最佳方式。)
const Territory = ({ tD }) => {
const [color, setColor] = useState('red')
const [troops, setTroops] = useState(21)
return (
<>
<input type="text" />
<path fill-rule="evenodd" clip-rule="evenodd" d={tD} fill={color} stroke="black" />
</>
);
};
export default Territory;
const Map = () => {
return (
<svg width="1397" height="686" viewBox="0 0 1397 686" fill="none" xmlns="http://www.w3.org/2000/svg">
{territories.map(territory => (
<Territory key={territory.id} tD={territory.tD} />
))}
</svg>
);
};
我想在每个领土的地图输入或标签中添加可见的部队(数字)。像这样的 map with inputs
可以吗?构建具有“部队”等道具的领土组件的最佳方法是什么
非常感谢帮助我的人。
您将 HTML <input />
正常渲染为 svg
的一部分,这不起作用。如果任何东西不是 svg
的一部分,并且您将其渲染为 svg
的子级,那么您必须将其包装为 foreignObject.
区域组件
const Territory = ({ tD }) => {
const [color, setColor] = useState('red')
const [troops, setTroops] = useState(21)
return (
<g>
<foreignObject x="40" y="40" width="100" height="100">
<div xmlns="http://www.w3.org/1999/xhtml">
<input type="text" />
</div>
</foreignObject>
<path fill-rule="evenodd" clip-rule="evenodd" d={tD} fill={color} stroke="black" />
</g>
);
};
注:
- 不要忘记
height
和width
属性。您可能还需要x
&y
。 - 不要忘记容器 HTML 元素上的
xmlns="http://www.w3.org/1999/xhtml"
。 - 您可以使用
svg <g />
标签对元素进行分组。