條件渲染
判斷條件一定是 bool
類型才會渲染舟陆,false
垄开、null
肺樟、undefined
class LoginForm extends React.Component {
constructor(props) {
super(props);
this.state = {
username: "",
pwd: "",
};
}
handleUserNameChange(e) {
this.setState({
username: e.target.value,
});
}
handlePwdChange(e) {
this.setState({
pwd: e.target.value,
});
}
login() {
const { username, pwd } = this.state;
// 通過 props 將用戶信息傳遞給 父組件
this.props.login(username, pwd);
}
render() {
return (
<div>
<div>
<span>用戶名:</span>
<input type="text" onChange={(e) => this.handleUserNameChange(e)} />
</div>
<div>
<span>密碼:</span>
<input type="password" onChange={this.handlePwdChange.bind(this)} />
</div>
<button onClick={() => this.login()}>提交</button>
</div>
);
}
}
class Welcome extends React.Component {
render() {
return (
<div>
<h1>歡迎登錄</h1>
<button onClick={() => this.props.logout()}>退出登錄</button>
</div>
);
}
}
class Tip extends React.Component {
render() {
const { tipShow } = this.props;
if (!tipShow) {
return null;
}
return <p>tip</p>;
}
}
class App extends React.Component {
constructor() {
super();
this.state = { logged: false, tipShow: false };
}
login = (username, pwd) => {
if (username === "123" && pwd === "123") {
// 登錄成功會重置信息
this.setState({
logged: true,
tipShow: true,
});
}
};
logout = () => {
this.setState({
logged: false,
tipShow: false,
});
};
render() {
const { logged, tipShow } = this.state;
return !logged ? (
<LoginForm login={this.login} />
) : (
<div>
<Welcome logout={this.logout} />
<Tip tipShow={tipShow} />
</div>
);
}
}
ReactDOM.render(<App />, document.querySelector("#app"));
列表渲染
報錯信息:Each child in a list should have a unique "key" prop.
原因:列表中每個子元素都必需一個唯一的 key
屬性值
-
key
是React
查看元素是否改變的一個唯一標識 -
key
必須在兄弟節(jié)點中唯一缴罗,確定的(兄弟結果是一個列表中的兄弟元素)
為什么不建議使用 index
作為 key
值宝恶?(建議在列表順序不改變乘综、元素不增刪的情況下使用 index
)
列表項增刪或順序改變了憎账,index
的對應項就會改變,key
對應的項還是之前列表對應元素的值卡辰,導致狀態(tài)混亂胞皱,查找元素性能就會變差
好的做法:
如果列表是靜態(tài)的,不可操作的九妈,可以選擇 index
作為 key
反砌,但也不推薦;
很有可能這個列表在以后維護擴展的時候允蚣,有可能變更為可操作的列表
- 盡量避免使用
index
- 可以用數(shù)據(jù)的
ID
(也有可能變化) - 使用動態(tài)生成的靜態(tài)
ID
:nanoid
import { nanoid } from "nanoid";
class ListTitle extends React.Component {
render() {
return (
<thead>
<tr>
<td>Key</td>
<td>id</td>
<td>name</td>
</tr>
</thead>
);
}
}
class ListItem extends React.Component {
render() {
const { sid, item } = this.props;
return (
<tr>
<td>{sid}</td>
<td>{item.id}</td>
<td>{item.name}</td>
</tr>
);
}
}
class App extends React.Component {
state = {
arr: [
{
id: 1,
name: "zs",
},
{
id: 2,
name: "zs2",
},
{
id: 3,
name: "zs3",
},
{
id: 4,
name: "zs4",
},
{
id: 5,
name: "zs5",
},
],
};
render() {
return (
<table border={1}>
<ListTitle />
<tbody>
{
// 如果多層嵌套map的話于颖,盡量把map結果抽離出子組件,提升性能
this.state.arr.map((item) => {
const sid = nanoid();
// key 不會作為屬性傳遞給子組件嚷兔,必須顯示傳遞 key 值
// 原因:防止開發(fā)者在邏輯中對key值進行操作
return <ListItem key={sid} sid={sid} item={item} />;
})}
</tbody>
</table>
);
}
}
ReactDOM.render(<App />, document.querySelector("#app"));