1:新建一项目 npx create--react-app lesson21
2:删除lesson21里面src目录中所有内容
3:分别新建四个js文件
index.js App.js child1.js child2.js
4:分别写入如下代码
index.js
import React from 'react'
import ReactDom from "react-dom";
import App from "./App";
ReactDom.render(<App></App>,document.getElementById("root"));
App.js
import React, { Component } from 'react'
import Child1 from "./Child1";
import Child2 from './Child2';
export default class App extends Component {
render() {
return (
<div>
<Child1></Child1>
<Child2></Child2>
</div>
)
}
}
Child1.js
import React, { Component, Fragment } from 'react'
export default class Child1 extends Component {
render() {
return (
<div>
我是子组件1
</div>
)
}
}
Child2.js
import React, { Component } from 'react'
export default class Child2 extends Component {
render() {
return (
<div>
我是子组件2
</div>
)
}
}
完成运行 可以看到页面组件之间的嵌套效果 接下来在Child1中学习判断 判断年龄是否成年
使用三元运算符
补充一个知识点 占位符 有的时候不想显示下图红框的div
可以使用<></> 或者<Fragment></Fragment>代码如下
结果如图
接着我们改写代码如下
import React, { Component, Fragment } from 'react'
export default class Child1 extends Component {
constructor(props){
super(props);
this.state={
userage:18,
score:Math.round(Math.random()*100)
}
}
render() {
var result = null;
if(this.state.score>=60){
result = <span title="66">{this.state.score}及格</span>
}else{
result = <span title="66">{this.state.score}不及格</span>
}
return (
<>
{this.state.userage>=18?"成年":"未成年"}
{result}
</>
)
}
}
代码讲解如图
继续引入循环继续改写代码
import React, { Component, Fragment } from 'react'
export default class Child1 extends Component {
constructor(props){
super(props);
this.state={
userage:18,
score:Math.round(Math.random()*100),
userlist:[
{id:1,username:"leson"},
{id:2,username:"lili"}
]
}
}
render() {
const list = this.state.userlist.map(item=><ul key={item.id}><li>{item.id}</li><li>{item.username}</li></ul>)
var result = null;
if(this.state.score>=60){
result = <span title="66">{this.state.score}及格</span>
}else{
result = <span title="66">{this.state.score}不及格</span>
}
return (
<>
{list}
{this.state.userage>=18?"成年":"未成年"}
{result}
</>
)
}
}
代码注释如下