【问题标题】:How can I get a full working example with React 0.14 and Typescript 1.6.2 and Rails 4.2如何使用 React 0.14 和 Typescript 1.6.2 和 Rails 4.2 获得完整的工作示例
【发布时间】:2016-02-16 03:19:02
【问题描述】:

有没有人有最新(稳定)React 的工作示例,使用最新(稳定)Typescript 和 Rails 4.2?

使用 typescript-rails gem (https://github.com/typescript-ruby/typescript-rails) 和 Rails 4.2 可以通过资产管道正常工作。

例如,这些示例都不起作用: http://blog.mgechev.com/2015/07/05/using-jsx-react-with-typescript/ http://staxmanade.com/2015/08/playing-with-typescript-and-jsx/

遇到的各种错误是:(基于您使用的来自https://github.com/DefinitelyTyped 的示例,以及您使用的绝对类型react.d.ts)

/var/folders/ng/f_1__7m57x9bmprw7lvpz7180000gn/T/typescript-node20151114-27510-1dvq95y.ts(18,1):错误 TS2304:找不到名称“ReactDOM”。

【问题讨论】:

标签: reactjs typescript


【解决方案1】:

一天后我想通了。

准备

步骤 0。

确保您正确安装了 typescript-rails gem 并验证它与 Rails 4.2 资产管道一起使用。 (见:https://github.com/typescript-ruby/typescript-rails

第 1 步。

typescript-rails (0.6.2) gem 中有一个带有--jsx react 的错误。要解决此问题,请创建 gem 文件的本地副本并将其保存到:

vendor/typescript-rails-0.6.2

然后通过 gemfile 告诉您的 Rails 应用程序直接包含它:

gem 'typescript-rails',  :path => "vendor/typescript-rails-0.6.2"

现在,我们从以下位置修改 typescript-rails:

# vendor/typescript-rails-0.6.2/lib/typescript/rails/compiler.rb
# 
# ... (line 69):
self.default_options = %w(--target ES5 --noImplicitAny)
# ....
#

收件人:

# vendor/typescript-rails-0.6.2/lib/typescript/rails/compiler.rb
# 
# ... (line 69):
self.default_options = %w(--target ES5 --jsx react)
# ....
#

第 2 步。

将以下 react 文件复制到您的 app/assets/javascript 文件夹:

https://fb.me/react-0.14.2.js 和... https://fb.me/react-dom-0.14.2.js

更新您的 application.js 以包含这 2 个反应文件:

 // app/assets/javascripts/application.js:
 // ...
 //= require react-0.14.2.js
 //= require react-dom-0.14.2.js
 // ...

现在我们已经完成了初始设置(一切应该仍然可以使用上面的更改)

步骤

步骤 0。

https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/react 复制所有文件到 app/assets/javascripts/typing (我之前缺少的关键步骤)

步骤 1. 创建一个文件 app/assets/javascript/home.ts(由 HomeController 加载),其内容为:

/// <reference path="typing/react-global.d.ts"/>
/// <reference path="my_component.tsx"/>

第 2 步。创建一个文件 app/assets/javascript/my_component.tsx,其内容为:

/// <reference path="./typing/react-global.d.ts" />

interface HelloWorldProps {
  name: string;
}

var HelloMessage = React.createClass<HelloWorldProps, any>({
  render: function() {
    return <div>Hello {this.props.name}</div>;
  }
});

var mountNode = document.getElementById('id_of_mount_dom_element');
ReactDOM.render(<HelloMessage name="John" />, mountNode);

第 3 步。

确保您有一个文件 home/index.html.erb 文件一个带有 id 'id_of_mount_dom_element' 的 React 根 div 元素。然后你会在加载页面时看到组件挂载(比如http://127.0.0.1:3000/home

Hello John

完成

【讨论】:

    猜你喜欢
    • 2011-11-14
    • 2016-02-04
    • 2018-03-11
    • 1970-01-01
    • 2020-08-19
    • 2016-04-24
    • 2012-11-30
    • 2015-06-08
    • 2016-06-28
    相关资源
    最近更新 更多