我正在尝试将此动画 SVG 制作为 React JS 中的一个组件,但我找不到解决方案。
如果可能,我想避免将所有样式移动到单独的 .css 文件中。如何在 React JS 中将 SVG 作为组件导入但保留所有样式?
SVG
<svg class="spinner" width="150" height="150" viewBox="0 0 100 100">
<circle class="background" r="24" cx="50" cy="50"></circle>
<path
class="line"
d="M 37.5,50 C 37.5,43.096441 43.096441,37.5 50,37.5 C 56.903559,37.5 62.5,43.096441 62.5,50 C 62.5,56.903559 56.903559,62.5 50,62.5 C 43.096441,62.5 37.5,56.903559 37.5,50"
></path>
</svg>
CSS
body {
align-items: center;
background: #333;
display: flex;
flex-direction: column;
justify-content: center;
height: 100vh;
}
.background {
fill: #555;
}
.line {
animation: PacMan 5s infinite;
fill: none;
stroke: #d26188;
stroke-width: 25;
}
.spinner {
animation: Spin 2s infinite linear;
}
@keyframes PacMan {
0% {
stroke-dasharray: 79px 79;
}
50% {
stroke-dasharray: 1px 79;
}
100% {
stroke-dasharray: 79px 79;
}
}
@keyframes Spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
最佳答案
您也可以在组件内内联样式。样式应该是一个字符串(用反引号括起来,因为文本是多行的),所以 React 不会尝试将大括号解析为表达式。
注意:样式中嵌入的类名会影响页面上的所有内容,因此您应该添加命名空间,或以其他形式使它们唯一。
const Spinner = () => (
<React.Fragment>
<style>
{`
.spinner .background {
fill: #555;
}
.spinner .line {
animation: PacMan 5s infinite;
fill: none;
stroke: #d26188;
stroke-width: 25;
}
.spinner .spinner {
animation: Spin 2s infinite linear;
}
@keyframes PacMan {
0% {
stroke-dasharray: 79px 79;
}
50% {
stroke-dasharray: 1px 79;
}
100% {
stroke-dasharray: 79px 79;
}
}
@keyframes Spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
`}
</style>
<svg class="spinner" width="150" height="150" viewBox="0 0 100 100">
<circle class="background" r="24" cx="50" cy="50"></circle>
<path
class="line"
d="M 37.5,50 C 37.5,43.096441 43.096441,37.5 50,37.5 C 56.903559,37.5 62.5,43.096441 62.5,50 C 62.5,56.903559 56.903559,62.5 50,62.5 C 43.096441,62.5 37.5,56.903559 37.5,50"
></path>
</svg>
</React.Fragment>
)
ReactDOM.render(
<Spinner />,
root
)
body {
align-items: center;
background: #333;
display: flex;
flex-direction: column;
justify-content: center;
height: 100vh;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
关于javascript - 动画 SVG 图标作为 React JS 中的组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59003239/