demo
https://gitee.com/zyzcos/react-study
博客
https://zyzcos.gitee.io/
条件渲染
其实就是在组件内写
判断逻辑
进行条件渲染。
function FirstCome(props){
return <h1>Welcome , { props.name }</h1>
}
function UnFirstCome(props){
return <h1>Welcom back , { props.name }</h1>
}
function showWelcome(props){
const userName = props.name;
const isFirstTime = props.timeFlag;
if(isFirstTime){
return <FirstCome name = { userName } />
}else{
return <UnFirstCome name = { userName } />
}
}
有状态组件
个人理解:就是具有条件渲染的组件,称为状态组件。
// 根据上面的代码,创建一个具有状态的组件 BootScreen
function Introduce(props){
return <h1>这里是一个专注于分享的地方</h1>
}
function BootScreen(props){
const userName = props.name;
const FirstTime = props.timeFlag
// 进行条件渲染,将渲染结果存在元素welcome中
let welcome
if(isFirstTime){
welcome = <FirstCome name = { userName } />
}else{
welcome = <UnFirstCome name = { userName } />
}
// 进行组件的渲染返回
return (
<div>
<Introduce />
{ weclome }
</div>
)
}
JSX内联条件渲染
之前学JSX的时候就讲过,{}在其中可以书写JS逻辑代码,就此原理,可以在JSX模板内进行内联渲染
- 通过运算符
&&
实现
//构建一个消息未读的提示组件
function UnReadBox(props){
const unreadMessages = props.unreadMessages;
return(
<div>
{
unreadMessages.length > 0 &&
<h1>您有 { unreadMessage.length } 条信息未读</h1>
}
</div>
)
}
- 通过三目运算符
FLAG ? VALUE1 : VALUE2
实现
//构建一个消息未读的提示组件
function UnReadBox(props){
const unreadMessages = props.unreadMessages;
const unreadBox = <h1>您有 { unreadMessage.length } 条信息未读</h1>;
const normalBox = <h1>您暂无未读消息</h1>
return(
<div>
{
unreadMessages.length > 0 ? unreadBox : normalBox
}
</div>
)
}
阻止渲染
可以通过
return null
来阻止渲染。但是阻止渲染不会影响组件的生命周期。
下面通过一个显示和关闭未读消息的组件来测试一下
function UnReadBox(props) {
const isShow = props.isShow;
const unreadMessages = props.unreadMessages;
const unreadBox = <h1>您有{ unreadMessages.length }条信息未读</h1>;
const normalBox = <h1> 您暂无未读消息 </h1>
if(isShow){
if (unreadMessages.length > 0) {
return unreadBox;
} else {
return normalBox;
}
}else{
return null;
}
}
//用来控制是否显示未读盒子
class BoxControl extends React.Component {
constructor(props) {
super(props);
this.state = { showBox: true , message:['1','2','3','4'] };
this.handleToggleClick = this.handleToggleClick.bind(this);
this.handleClearMessage = this.handleClearMessage.bind(this);
}
// 是否显示未读盒子
handleToggleClick(){
this.setState(state=>({
showBox:!state.showBox
}));
}
// 清除未读消息
handleClearMessage(){
this.setState(state=>({
messag