React学习笔记之条件渲染一

前言

在React中,你可以创建不同的组件各自封装你需要的东西。之后你可以只渲染其中的一部分,这取决于应用的state(状态)。下面就来看看详细的介绍:

条件渲染

可以根据state的值进行组件的条件渲染。例如:

rush:js;"> function Greeting(props) { const isLoggedIn = props.isLoggedIn; if (isLoggedIn) { return ; } return ; }

ReactDOM.render(
// Try changing to isLoggedIn={true}:

,document.getElementById('root') );

你还可以用变量去存储组件,以便进行条件筛选,使得渲染函数的返回值更加清爽,例如:

rush:js;"> class LoginControl extends React.Component { constructor(props) { super(props); this.handleLoginClick = this.handleLoginClick.bind(this); this.handlelogoutClick = this.handlelogoutClick.bind(this); this.state = {isLoggedIn: false}; }

handleLoginClick() {
this.setState({isLoggedIn: true});
}

handlelogoutClick() {
this.setState({isLoggedIn: false});
}

render() {
const isLoggedIn = this.state.isLoggedIn;

let button = null;
if (isLoggedIn) {
button = ;
} else {
button = ;
}

return (

{button}
); } }

ReactDOM.render(

,document.getElementById('root') );

还可以使用短操作符来实现条件筛选,可以用更短的代码写出渲染结果。例如&&来替代if,?:来替代if else,例如:

rush:js;"> function MailBox(props) { const unreadMessages = props.unreadMessages; return (

Hello!

{unreadMessages.length > 0 &&

You have {unreadMessages.length} unread messages.

}
); }

const messages = ['React','Re: React','Re:Re: React'];
ReactDOM.render(

,document.getElementById('root') );
rush:js;"> render() { const isLoggedIn = this.state.isLoggedIn; return (
The user is {isLoggedIn ? 'currently' : 'not'} logged in.
); }

这种跟更大的表达式的写法也可以,但是不推荐,因为代码就不是很直观了。

rush:js;"> render() { const isLoggedIn = this.state.isLoggedIn; return (
{isLoggedIn ? ( ) : ( )}
); }

如果组件有时候需要渲染出来,而有时候不需要渲染出来,在不需要渲染的时候返回null即可。例如:

rush:js;"> function WarningBanner(props) { if (!props.warn) { return null; }

return (
<div className="warning">
Warning!

); }

class Page extends React.Component {
constructor(props) {
super(props);
this.state = {showWarning: true}
this.handletoggleClick = this.handletoggleClick.bind(this);
}

handletoggleClick() {
this.setState(prevstate => ({
showWarning: !prevstate.showWarning
}));
}

render() {
return (

); } }

ReactDOM.render(

,document.getElementById('root') );

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如有疑问大家可以留言交流,谢谢大家对编程之家的支持

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...