react直接在页面引入的问题

各位,问个问题,react直接在页面中引入的话,一个文件里面的多个components如何单独的分离成各个小的componen组件呢,

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
    <script src="./bower_components/react/react.min.js" charset="utf-8"></script>
    <script src="./bower_components/react/react-dom.min.js" charset="utf-8"></script>
    <script src="./bower_components/babel/browser.min.js" charset="utf-8"></script>
    <script src="./components/scheduleComponent.js" type="text/babel" charset="utf-8"></script>
    <script src="./index.js" type="text/babel" charset="utf-8"></script>
</head>

<body>
    <div id="root" class="container"></div>
</body>

</html>

scheduleComponent.js

var ScheduleComponent  = React.createClass({
    render () {
        return (
            <div>Hello</div>
        )
    }
})

index.js

function Hello(props) {
    return (
        <div className="col-md-4">
            <ScheduleComponent/>
        </div>
    )
}

ReactDOM.render(
    <Hello/>, document.getElementById('root'))

clipboard.png

新手表示为何不能这样做,在线等各位好心人求解

阅读 6.8k
5 个回答
新手上路,请多包涵

在scheduleComponent.js末尾添加:

module.exports = ScheduleComponent;

然后在index.js首部添加:

var ScheduleComponent = require('./scheduleComponent.js');
新手上路,请多包涵

index导入那个组件

模块化的话你就语言使用模块导出导入,可以使用es6的export和import

既然用了babel你就用es6语法导入导出呗

// End of scheduleComponent
export ScheduleComponent;
// Head of index
import {ScheduleComponent} from './components/scheduleComponent.js';

实在不行你就把模块都仍全局变量好了

window.ScheduleComponent = ScheduleComponent;
const ScheduleComponent = window.ScheduleComponent;
推荐问题
宣传栏