如何将第三方React组件导入Typescript TSX文件?
我有一个非常大的JavaScript前端项目,它使用:
我想添加两个第三方React组件:
为了清楚说明,我创建了一个基本的轻量级项目,它复制了GitHub上的基本工具(https://github.com/mgrackerl/react-requirejs-example),您可以在其中试用代码。
关于示例项目文件:
要使用DatePicker,我想要的最终结果是这样的:
import React = require('react');
import ReactDOM = require('react-dom');
import DatePicker = require('react-datepicker');
let handleChange = function(date: Date) {
this.setState({
startDate: date
});
};
var myDivElement = <div>
<DatePicker
selected={new Date()}
onChange={handleChange} />
</div>;
ReactDOM.render(myDivElement, document.getElementById('example'));
答案 0 :(得分:0)
在深入研究GitHub问题后,我最终导入了DatePicker组件。
提交: https://github.com/mgrackerl/react-requirejs-example/commit/4afcd28db1ee0f5a9fa0fe65bf505e521814f562
有关导入react-datepicker组件的注意事项:
1)必须将打字文件带到项目中以使Typescript编译器工作(github项目目录:typings / react-datepicker)
2)对于DatePicker组件,我们必须使用MomentJS(http://momentjs.com/)而不是Javascript Date对象。
scripts / main.tsx文件:
/// <reference path="../typings/index.d.ts" />
import React = require('react');
import ReactDOM = require('react-dom');
import DatePicker = require('react-datepicker'); // 3rd party DatePicker component
import moment = require('moment'); // use for the DatePicker component
// callback function for DatePicker onChange event
let handleChange = function(){
return function(date:any) {
console.log("data is: " + date);
};
}
// Create new React component that consumes 3rd party DatePicker component
var myDivElement = <div>
<DatePicker
selected={moment()}
onChange={handleChange} />
</div>;
// Render newly create "myDivElement" component
ReactDOM.render(myDivElement, document.getElementById('example'));
当然设置RequireJS设置:
require.config({
"urlArgs": "v=01",
"baseUrl": "",
"paths": {
"react": "node_modules/react/dist/react",
"react-dom": "node_modules/react-dom/dist/react-dom",
"moment": "node_modules/moment/min/moment.min",
"react-onclickoutside": "node_modules/react-onclickoutside/index",
"react-datepicker": "node_modules/react-datepicker/dist/react-datepicker",
"main": "scripts/main",
},
"shim": {
"datatable": {
"deps": ['jquery']
},
"dtbootstrap": {
"deps": ['datatable']
},
},
jsx: {
fileExtension: ".js",
}
});