1.为什么要组件化?
前端页面组件化优点:复用性、易维护、可读性
2.如何写组件?
(1). 单个组件
a. 需要继承React.Component
b.需要有一个render
import React, { Component } from 'react';
import Home from './components/Home'
class App extends Component {
render() {
return (
<div className="App">
<Home a={1} b={{nickname: 'zhangsan'}}/>
</div>
);
}
}
export default App;
(2). 组件传参、状态、事件处理
a. 组件传参
父组件传值:变量或对象 <Home a={1} b={{nickname: 'zhangsan'}}/>
子组件接收:this.props.a; this.props.b.nickname
b.组件状态
通过 this.setState()改变值
c.事件交互
(I). this.fn.bind(this) ------- fn()
(II). this.fn ------ fn = () => {} //不带参数
(III). () => this.fn(params) ------- fn = (params) => {}
注意: react事件与原生和vue的区别
onclick(原生)------------ @click(vue) ----------- onClick(react)
import React, { Component } from 'react';
class Home extends Component {
constructor(...args) {
super(...args);
this.state = {
name: 'david',
age: 18
};
}
addAge = () => {
this.setState({
age: this.state.age + 1
})
}
addAge2 = (value) => {
this.setState({
age: this.state.age + value
})
}
addAge3 () {
this.setState({
age: this.state.age + 3
})
}
render() {
return (
<div>
<header>
<div className="title">header</div>
</header>
<section>
<button onClick={this.addAge}>+1</button>
<button onClick={() => this.addAge2(2)}>+2</button>
<button onClick={this.addAge3.bind(this)}>+3</button>
<div>{this.state.name}:{this.state.age}</div>
<div>{this.props.a}</div>
<div>{this.props.b.nickname}</div>
</section>
<footer>footer</footer>
</div>
);
}
}
export default Home;