列表渲染、条件渲染、双向绑定:
App.js:
import React, { Component } from 'react';
import './App.css';
import MyList from "./Components/MyList/MyList"
class App extends Component {
constructor(props){
super(props);
this.state = {
num: 1
}
}
render() {
return (
<div className="App">
<p>{this.state.num}</p>
<MyList num={this.state.num} changeNum={this.changeNumMethod}></MyList>
</div>
);
}
changeNumMethod = n=>{
this.setState({
num: n
});
}
}
export default App;
MyList.js
import React from "react"
import "./MyList.css"
class MyList extends React.Component{
constructor(props){
super(props);
this.state = {
txt: "初始文本",
show: true,
books: [
{name:"水浒传",price:88,sellOut:false},
{name:"西游记",price:78,sellOut:true},
{name:"红楼梦",price:58.8,sellOut:false}
]
}
}
render(h) {
return (
<div className="MyList">
{/* 列表渲染 */}
<table>
<caption>售卖书籍</caption>
<thead>
<tr>
<th>编号</th>
<th>书名</th>
<th>价格</th>
<th>购买</th>
</tr>
</thead>
<tbody>
{/* 在 react 中,通过数组的 map 方法进行列表渲染。使用 map 返回一个 html 数组,插入到页面中(为什么不使用 forEach 遍历,因为它没有返回值) */}
{this.state.books.map((item,index)=>{
return (
<tr key={index}>
<td>{index+1}</td>
<td>{item.name}</td>
<td>{item.price}</td>
<td>{item.sellOut?<span>售罄</span>:<button i={index} onClick={(e)=>{this.buyClick(e,index)}}>购买</button>}</td>
</tr>
)
})}
</tbody>
</table>
{/* react中没有直接的双向绑定,必须通过手动绑定值和事件监听 */}
<input type="text" value={this.state.txt} onChange={this.txtChange}/>
<p>{this.state.txt}</p>
{/* 对于单选和多选框,需要绑定checked属性+onChange */}
<input type="checkbox" checked={this.state.show} onChange={e=>{this.setState({
show: e.target.checked
})}} /> 开关
{/* react模板中不能直接渲染布尔值 */}
<p>{true}|{"true"}</p>
{/* react模板中没有条件渲染,只能使用三目运算符进行条件渲染 */}
{this.state.show?<h1>开业大吉</h1>:<p>关门大吉</p>}
<p>{this.props.num}</p>
<button onClick={this.numClick}>改变num</button>
</div>
)
}
// 想给按钮事件传递参数,有两种做法:
// 1.给标签设置属性,通过事件对象event进行传递(e.target.getAttribute("i"))
// 2.给按钮事件先绑定一个箭头函数(默认有个参数event),然后在箭头函数中调用事件方法(onClick={(e)=>{this.buyClick(e,index)})
buyClick = (e,index)=>{
// console.log(this);
// console.log(e.target.getAttribute("i"));
console.log(e,index);
alert(index);
}
txtChange = e=>{
this.setState({
txt:e.target.value
})
}
numClick = e=>{
this.props.changeNum(this.props.num+1);
}
}
export default MyList