React入门
一、使用react框架需要引入
<script src="./lib/react.development.js"></script>
<script src="./lib/react-dom.development.js"></script>
<script src="./lib/babel.min.js"></script>
定义一个组件:
(1)通过function定义一个组件
需要有一个返回值作为组件的返回数据
function H() {
return (<h1>我是一个标题</h1>)
}
在页面上渲染组件,参数一:组件名,参数二:挂载节点
ReactDOM.render(<H/>, document.getElementById('app'))
结果:
给组件传参:
ReactDOM.render(<H label="给组件H(props)传值"/>, document.getElementById('app'))
结果:
(2)通过class定义一个组件
组件需要继承在React.Component上,组件内部有一个render方法,
class C extends React.Component {
// render渲染函数,用来在页面上展示数据
render() {
return (<h5>我是组件C</h5>)
}
}
简单的组件传值:
class定义的组件中都有一个state方法,要想改变state,需要调用setState方法
结果:
使用className关键字设置样式:
<style>
.dp {
color: orangered;
}
</style>
结果:
从本地获取数据:
const { Component } = React;//利用解构赋值,获取React中的Component,以后React.Component可以简写为Component
假数据:
const list = [
{
name: 'Tom',
age: 18
}, {
name: 'Jerry',
age: 19
}, {
name: '巴斯光年',
age: 29
}
]
得到数据:
方法一:
class People extends Component {
render() {
return (
<div>
{list.map((item, index) => <p key={index}>{item.name}</p>)}
</div>
)
}
}
方法二:
class People extends Component {
render() {
return (
<div>
{
list.map((item, index) => {
return (
<div key ={index}>
<p>名字是:{item.name},今年{item.age}岁了</p>
</div>
)
})
}
</div>
)
}
}
结果:
从服务器获取数据:
class Products extends Component {
constructor(props) {//构造函数,初始化
super(props)
this.state = { //每一个class定义的组件都有一个state方法
products: [],
}
axios.get('http://api.cat-shop.penkuoer.com/api/v1/products')
.then(res => {
//改变state,需要使用setState方法
this.setState({
products: res.data.products,
})
})
}
//当state数据改变的时候会重新调用render函数
// 使用map循环生成数据
render() {
return (
<div>
{
this.state.products.map(product => {
return (
<div key={product._id}>
<img src= {'http://api.cat-shop.penkuoer.com' + product.coverImg} className="size"/>
<p>{product.name}</p>
</div>
)
})
}
</div>
)
}
}
父组件与子组件间的传值:
(1)父组件向自组件传值
父组件通过props传递数据到子组件,在子组件中使用this.props进行调用
在通过设置属性的方法向子组件传值后,可以查看到props中多了新增的属性和属性值
结果:
在子组件中使用this.props进行调用
结果:
(2)子组件向父组件传值
子组件向父组件传值使用方法调用(子组件调用父组件中的方法)
结果:
例二:
const { Component } = React;
class Counter extends Component {
constructor() {
super()
this.state = {
count: 1,
}
}
clickHandle() {
this.setState({
count: this.state.count + 1
}, function() { // setState的参数二中的回调函数表示状态改变完成
this.props.changeCurrentCount(this.state.count)
})
}
render() {
return (<button onClick={this.clickHandle.bind(this)}>值为:{this.state.count}</button>)
}
}
class App extends Component {
constructor(props) {
super(props)
this.state = {
currentCount: 1,
}
}
changeCurrentCountHandle(currentCount) {
this.setState({
currentCount
})
}
render() {
return (<div>
<h4>当前计数器的值为:{this.state.currentCount}</h4>
<Counter changeCurrentCount = {this.changeCurrentCountHandle.bind(this)} />
</div>)
}
}
ReactDOM.render(<App />, document.getElementById('app'))