React.js学习入门

官网:https://reactjs.org

创建项目

1
2
3
npx create-react-app my-app
cd my-app
yarn start

打开:http://127.0.0.1:3000/

目录结构

public:中默认存在index.html文件,只有一个id=rootdiv,这是应用组件的根节点,在react开发中我们不需要去直接编写html文件,而是通过js生成页面,渲染到这个根节点中
src:存放css与js
index.js:整个工程的入口,可以看到,将<App />组件渲染到了index.htmlroot节点里

Hello World

基本语法

1
2
3
4
ReactDOM.render(
<h1>Hello, world!</h1>,
document.getElementById('root')
);

项目集成

hello.js

1
2
3
4
5
6
7
8
9
import React from 'react';

function Hello() {
return (
<h1>Hello, world!</h1>
);
}

export default Hello;

index.js

1
2
3
4
5
6
7
8
9
10
11
12
13
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
//import App from './App';
import Hello from './hello';
import * as serviceWorker from './serviceWorker';

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

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();

React中常见的ES6写法

引入模块用import实现:

1
import Hello from './base/hello';

导出模块用export default实现:

1
export default Hello

定义组件用继承自React.Component的class来实现:

1
2
3
4
5
class Hello extends React.Component {
render() {
...
}
}

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :