gpt4 book ai didi

javascript - 将 class= 属性添加到已定义的

转载 作者:行者123 更新时间:2023-12-04 15:06:18 25 4
gpt4 key购买 nike

假设我有图标:

//myicons.js
import React from "react";

export const ico = {
someIcon:
<svg ... >
...
</svg>,

还有一个使用一些图标的组件:

import React, { Component } from "react";
import { ico } from "./myicons";

export class MyIcon extends Component {
render () {
return ico[this.props.which];
}
}

还有使用图标的地方:

//some render func
return (
<div ... >
<MyIcon which="someIcon"/>
...
</div>
);

假设我要添加一个 css 类:

<MyIcon which="someIcon" className="blahblah" />

..如何让 DOM 最终包含 <svg class="blahblah"即如何添加 <MyIcon className="blahblah" 中给出的 blahblah 类到 class= <svg 的属性由 ico[this.props.which] 返回?

如果有帮助,这就是最终从渲染返回的内容:

enter image description here

最佳答案

我会这样写:

import React from "react";

const getIconWithClass = (type, className) => {
switch (type) {
case "iconA":
return <svg className={className}>iconA</svg>;
case "iconB":
return <svg className={className}>iconB</svg>;
default:
return null;
}
};
class MyIcon extends React.Component {
render() {
const { which, className } = this.props;
return getIconWithClass(which, className);
}
}

const App = () => {
return (
<div>
<MyIcon which="iconA" className="bla-bla" />
</div>
);
};

export default App;

关于javascript - 将 class= 属性添加到已定义的 <svg>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66016020/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com