reactTowDay

React Tow Day

创建组件

在写react之前,肯定需要有创建组件的技能,那创建组件这里主要是使用两种方式进行创建,这两种方式分别是class类与函数式。

注:在创建组件中,需与vue相同,使用一个外层标签包裹。如下在return中都由一个div包裹。

class类创建方式:

1
2
3
4
5
6
7
import React from 'react'
class components extends React.Component {
render(){
return <div><h2>hello I`m class Component </h2></div>
}
}
export default components

函数式组件创建方式:

1
2
3
4
5
function components(){
return <div><h2>hello I`m funtion component </h2></div>
}

export default components

组件的使用,注:同一个文件级别下的话,直接进行使用即可,如果不同文件需先import。

1
2
3
4
5
6
7
8
9
10
11
12
import React,{Component} from 'react'
import Components form './index.js'
export default class App extends Component {
render() {
return (
<div>
// 引用组件
<Components></Components>
</div>
)
}
}

组件的样式

在组件开发时,好不好看归根于我们的css大法好不好。

所以在组件开发时,要怎么样进行添加样式呢?

行内样式

在我们的组件return前,可以使用行内直接编写样式。

在react中样式名称基本一致,只是在写样式时没有 ‘ - ‘ 使用这个符号。

如:在css中我们写背景颜色:background-color:red;
在react组件中是:backgroundColor:’red’,使用驼峰法进行编写。

外部CSS文件

使用行内样式写起来显得代码很乱,所以这个时候使用外部css文件引入,然后只要定义匹配的class是不是更好呢?

1.新增CSS文件,编写CSS代码
2.CSS代码引入相应的组件中 import ‘./index.css’
3.编写组件代码,这时就会自动使用css文件中的css

注:在react中,标签中不要使用class进行设置,而是使用className

1
2
3
4
5

<div class="active>这个是错误的写法 × </div>

<div className="active">这个是正确的写法 √ </div>

1
2
3
.active{
background-color:red;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import React,{Component} from "react";

import "./css/index.css";

export default class App extends Component {
render() {
var name = "react";
var styleObj = {
backgroundColor: "red"
}
return (
<div>
<div style={styleObj}>Hello {name} World Style red</div>
<div>
<h1 style={{backgroundColor:'yellow'}}>Hello {name} World I`m yellow</h1>
</div>
<div className="active">
<h1>Hello {name} World I`m from external css file</h1>
</div>
</div>
)
}
}

从上面代码可以看出,react与vue的写法差不多,但是又不同,vue使用双大括号,而react使用单大括号来解析变量。

react注释

在组件中怎么进行注释呢,添加了//与/* /统统不行。
对了!因为你在react的地盘,你只能用react的注释,只要在想注释的地方使用 {} ,并且在其中添加 // 或者/
/
如:
{
//这个是单行注释
/

这个是多行注释
*/
}

react事件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import React,{Component} from "react";

import "./css/index.css";

export default class App extends Component {
render() {
return (
<div>
<input></input>
<button onClick={ ()=>{
console.log("click");
} }>add</button>

<button onClick={ this.handleClick2 }>add2</button>

<button onClick={ this.handleClick3 }>add3</button>

<button onClick={ ()=>{
this.handleClick4(666)
} }>add4</button>
</div>
)
}

handleClick2(){
console.log('click2');
}

handleClick3 = () => {
console.log('click3');
}

handleClick4(item){
console.log('click4',item);
console.log('click4');
}
}