分类目录: html5
react简单双向数据绑定(2)
Post date:
Author: cyy
标签: react
Number of comments: no comments
vue中的v-if和v-for在react中的简单实现。
import React from 'react';
import './index.less';
/**
* 测试用
*/
class Hello extends React.PureComponent {
state = {
uname: 'cyy',
age: 50,
showList: true,
list: [{
name: "cyy",
age: 1
}, {
name: "cyy2",
age: 2
}, {
name: "cyy3",
age: 3
}]
};
handleAdd = (e) => {
let age = this.state.age + 1;
this.setState({ age: age });
};
handleMin = (e) => {
let age = this.state.age - 1;
this.setState({ age: age });
};
handleShow = (e) => {
let showList = !this.state.showList;
this.setState({ showList: showList });
};
render() {
const { list, showList } = this.state;
const items = [];
list.forEach((item, index) => {
const t = (
<div key={index}>
我是 {item.name}, 我 {item.age} 岁。
</div>
);
items.push(t);
});
const component = (
<div>{items}</div>
);
return (
<div className="app-container">
<h1>
hello~{this.state.uname}, age: {this.state.age}
</h1>
<button style={{ width: "100px" }} onClick={this.handleAdd}>+1</button>
<button style={{ width: "100px" }} onClick={this.handleMin}>-1</button>
<button style={{ width: "100px" }} onClick={this.handleShow}>{showList ? '隐藏' : '显示'}</button>
{ showList ? component : null}
</div>
);
}
}
export default Hello;