静态条件渲染
示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<style>
.h1 {
color: red;
}
.div1 {
width: 100px;
height: 100px;
background-color: pink;
}
</style>
</head>
<body>
<!-- react的容器 -->
<div id="app"></div>
</body>
</html>
<script type="text/babel">
class ComClass extends React.Component {
constructor() {
super();
//静态的条件渲染(注意:只能取消this.state = { a: xxx }进行演示)
this.state = { a: 1 }
// this.state = { a: 2 }
// this.state = { a: 3 }
}
render() {
//当this.state.a不同会渲染出对应的组件,静态条件渲染
if (this.state.a == 1) {
return <div>内容1</div>
} else if (this.state.a == 2) {
return <div>内容2</div>
} else {
return <div>内容3</div>
}
}
}
//不同的条件去return不同东西,达到渲染不同的东西,这就是条件渲染
ReactDOM.render(<ComClass />, document.querySelector("#app"));
</script>
动态条件渲染
示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<style>
.h1 {
color: red;
}
.div1 {
width: 100px;
height: 100px;
background-color: pink;
}
</style>
</head>
<body>
<!-- react的容器 -->
<div id="app"></div>
</body>
</html>
<script type="text/babel">
class ComClass extends React.Component {
constructor() {
super();
this.state = {
a: 1
}
}
render() {
let com;
//动态的条件渲染
//条件判断完,com会等于不同的东西,下面的{com}就会展示不同的div
if (this.state.a == 1) {
com = <div>内容1</div>
} else if (this.state.a == 2) {
com = <div>内容2</div>
} else {
com = <div>内容3</div>
}
return (
<div>
<button onClick={() => { this.setState({ a: 1 }) }}>按钮1</button>
<button onClick={() => { this.setState({ a: 2 }) }}>按钮2</button>
<button onClick={() => { this.setState({ a: 3 }) }}>按钮3</button>
{com}
</div>
)
}
}
//不同的条件去return不同东西,达到渲染不同的东西,这就是条件渲染
ReactDOM.render(<ComClass />, document.querySelector("#app"));
</script>