借助create-react-app
和JavaScript / TypeScript,我了解我能够按照以下说明“导入” SVG。我该如何使用ReasonML?
import { ReactComponent as Logo } from './logo.svg';
function App() {
return (
<div>
{/* Logo is an actual React component */}
<Logo />
</div>
);
}
答案 0 :(得分:3)
Create React App使用webpack将SVG文件转换为React组件。如果您将Reason与CRA结合使用,那么您要做的就是提供对所生成组件的绑定。但是,只有完全以某种特定方式编写import语句时,CRA才会将SVG转换为组件,而这不是BuckleScript输出import语句的方式。 (There's a GitHub issue about it here.)您必须使用原始JavaScript导入它,然后将其绑定到导入的值:
%bs.raw
{|import {ReactComponent as _Logo} from "./logo.svg"|};
module Logo = {
[@react.component] [@bs.val] external make: unit => React.element = "_Logo";
};
/* And we can use it like a regular component: */
[@react.component]
let make = () =>
<div>
<Logo />
</div>;
导入的SVG React组件接受
title
道具以及svg
元素接受的其他道具。
对于您要使用的其他任何道具,都必须将它们添加到external
绑定中。
如果您不使用CRA,则需要配置捆绑器以执行相同的转换。我对CRA的内部知识并不熟悉,但是this seems to be the relevant code from its webpack configuration.
答案 1 :(得分:3)
我们可以使用SVGR处理webpack的加载,然后像往常一样导入模块。
const webpack = require('webpack');
module.exports = {
entry: './src/index.js',
module: {
rules: [
//...
{
test: /\.svg$/,
use: ['@svgr/webpack'],
},
],
},
//...
};
module Logo = {
@bs.module(`../../../../src/img/logo.svg`) @react.component
external make: {.} => React.element = "default"
}
...
<Logo /> // works
答案 2 :(得分:1)
我是另一种不涉及webpack的解决方案的作者。 该工具可以将您的svg文件直接转换为.re文件:https://github.com/MoOx/react-from-svg 这可以创建用于react(dom)或react-native(-web)的文件(=>使用react-native-svg生成的文件)。 随时尝试:)
例如,您可以(从npm安装该工具时)
$ react-from-svg src/SVGs src/SVGs/components --with-native-for-reason --remove-fill
这会将文件从svg/SVGs
转换为React组件,并转换为src/SVGs/components
,从而与使用Reason语法的React Native兼容。
最后一个选项删除所有svg填充道具,以便您可以将它们用作图标。
请注意,生成的组件接受width
,height
和fill
道具,因此您可以在使用时对其进行调整。
最后一个好处:由于不涉及webpack,因此只有在更新SVG文件并直接在Node运行时中使用此代码时,才能使用此转换(将Reason的JSX转换为JS后会删除,因此可以直接使用该代码无需任何转换即可通过Node进行操作-对于小型静态网站/页面而言非常方便。)