react列表渲染并添加了点击事件demo01
匿名函数法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<meta http-equiv="X-UA-Compatible" content="ie=edge"/>
<title>循环数据</title>
</head>
<body>
<div id="app"></div>
<script src="./lib/babel.min.js"></script>
<script src="./lib/react.development.js"></script>
<script src="./lib/react-dom.development.js"></script>
<script type="text/babel">
const {Component} = React;
const movies = [
{
id: 1,
name: "我和我的祖国"
},
{
id: 2,
name: "中国机长"
},
{
id: 3,
name: "攀登者"
}]
class MovieList extends Component {
constructor(props) {
super(props);
this.state = {
movies,
};
this.clickHandle =this.clickHandle.bind(this);
}
clickHandle(m){
console.log(m)
}
// 循环展示列表的时候需要使用map不能用forEach
render() {
const {movies} = this.state;
return (
<div>
{movies.map(movie =>
<p data-p={movie.id} onClick={()=>this.clickHandle(movie) } key={movie.id}>
{movie.name}
</p>)}
</div>
)
}
}
class App extends Component {
render() {
return (
<div>
<h1>我是一个标题</h1>
<MovieList/>
</div>
);
}
}
ReactDOM.render(<App/>, document.getElementById('app'));
</script>
</body>
</html>
demo 02
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<meta http-equiv="X-UA-Compatible" content="ie=edge"/>
<title>循环数据</title>
</head>
<body>
<div id="app"></div>
<script src="./lib/babel.min.js"></script>
<script src="./lib/react.development.js"></script>
<script src="./lib/react-dom.development.js"></script>
<script type="text/babel">
const {Component} = React;
const movies = [
{
id: 1,
name: "我和我的祖国"
},
{
id: 2,
name: "中国机长"
},
{
id: 3,
name: "攀登者"
}]
class MovieList extends Component {
constructor(props) {
super(props);
this.state = {
movies,
};
this.clickHandle =this.clickHandle.bind(this);
}
clickHandle(e){
console.log(e.currentTarget.dataset)
}
// 循环展示列表的时候需要使用map不能用forEach
render() {
const {movies} = this.state;
return (
<div>
{movies.map(movie =>
<p data-p={movie.id} onClick={this.clickHandle } key={movie.id}>
{movie.name}
</p>)}
</div>
)
}
}
class App extends Component {
render() {
return (
<div>
<h1>我是一个标题</h1>
<MovieList/>
</div>
);
}
}
ReactDOM.render(<App/>, document.getElementById('app'));
</script>
</body>
</html>