导入图片的三种方式...
1) 如果您直接使用jsx.erb 或js.erb 文件...
var image_path = "<%= asset_path(my_image.png) %>"
OR
render: function() {
return (
<img src={"<%= asset_url('path/to/image.png') %>"} />
)
}
2) 作为道具通过.erb文件传递给.js.erb或.jsx.erb文件
在您的.erb 文件中
render_component('Component', img_src: image_url('the_path'))
在您的 .js.erb 或 .jsx.erb 文件中
render: function() {
return (
<img src={this.props.img_src} />
)
}
3) 推荐:使用.js和.jsx文件并使用视图文件.html.erb进行渲染
在查看文件example.html.erb
<%= react_component("Example", props: {}, prerender: false) %>
在.jsx 文件中Example.jsx
import React, { Component } from "react";
import Image from "<IMAGE_PATH>/image.png";
export default class Example extends Component {
constructor(props, _railsContext) {
super(props);
}
render(){
return(
<div>
<img src={Image} alt="example" />
</div>
)
}
}
您需要注册Example 组件。在你的app > javascript > packs > application.js
import ReactOnRails from "react-on-rails";
import Exmaple from "<COMPONENT_PATH>/Exmaple";
ReactOnRails.register({
Exmaple
});
来源:github