对于一个展现页面来说,有好几种展现状态,在React中,能够根据不一样的状态,渲染组件。也就是条件渲染。不一样于Vue的v-if,v-show等框架提供的api,React中的条件渲染的工做方式与JavaScript中条件工做的方式相同。
如下就是条件渲染的几种方法:
方法一:
建立两个组件,根据条件显示两个组件之一(if-else)
举例:
function OneRender(props) {
return <h1>Welcome one</h1>;
}
function TwoRender(props) {
return <h1>Welcome two.</h1>;
}
function Greeting(props) {
const isLoggedIn = props.isLoggedIn;
if (isLoggedIn) {
return <OneRender />;
}
return <TwoRender />;
}
ReactDOM.render(
// Try changing to isLoggedIn={true}:
<Greeting isLoggedIn={false} />,
document.getElementById('root')
);
复制代码
方法二:
使用变量来存储元素,这样能够有条件地渲染组件的部分,剩余部分保持不变。
举例:
function LoginButton(props) {
return (
<button onClick={props.onClick}> Login </button>
);
}
function LogoutButton(props) {
return (
<button onClick={props.onClick}> Logout </button>
);
}
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 = <LogoutButton onClick={this.handleLogoutClick} />;
} else {
button = <LoginButton onClick={this.handleLoginClick} />;
}
return (
<div>
<Greeting isLoggedIn={isLoggedIn} />
{button}
</div>
);
}
}
ReactDOM.render(
<LoginControl />,
document.getElementById('root')
);
复制代码
方法三:
行内判断是否渲染,将全部表达式括在花括号中,从而将其嵌入JSX中。
举例:
function Mailbox(props) {
const unreadMessages = props.unreadMessages;
return (
<div> <h1>Hello!</h1> {unreadMessages.length > 0 && <h2> You have {unreadMessages.length} unread messages. </h2> } </div>
);
}
const messages = ['React', 'Re: React', 'Re:Re: React'];
ReactDOM.render(
<Mailbox unreadMessages={messages} />, document.getElementById('root') ); 复制代码
方法四:
内联条件渲染元素使用JavaScript的三元表达式。
render() {
const isLoggedIn = this.state.isLoggedIn;
return (
<div> The user is <b>{isLoggedIn ? 'currently' : 'not'}</b> logged in. </div>
);
}
复制代码
方法五:
阻止组件渲染,在有些状况下,但愿某个组件隐藏自身,即便该组件是由另外一个组件渲染也是如此。能够返回null而不是其渲染输出。null从组件的render方法返回不会影响组件生命周期方法的触发。
function WarningBanner(props) {
if (!props.warn) {
return null;
}
return (
<div className="warning"> Warning! </div>
);
}
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 (
<div> <WarningBanner warn={this.state.showWarning} /> <button onClick={this.handleToggleClick}> {this.state.showWarning ? 'Hide' : 'Show'} </button> </div> ); } } ReactDOM.render( <Page />, document.getElementById('root') ); 复制代码
以上就是React的几种条件渲染的方法,在实际作项目当中,选哪种条件渲染能够根据本身的需求来进行选择。(ps:根据react官网翻译来,作个总结,加深本身对条件渲染的理解)。一块儿加油吧!