react-rails资产管道图像路径

时间:2018-06-30 11:05:34

标签: ruby-on-rails reactjs asset-pipeline react-rails

我正在使用react-rails gem,但在弄清楚如何从资产管道加载图像时遇到了麻烦。

我目前使用.js.jsx.erb扩展名来处理此问题,但据我所知这是非常规的。 (我正确吗?)

有时候,我只是使用一个空的div,并将div的background-image属性设置为我要使用的图像。

使用react-rails时加载图像以反应成分的最佳方法是什么?

1 个答案:

答案 0 :(得分:2)

有三种导入图像的方法...

1)如果您直接使用jsx.erbjs.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

相关问题