是否可以用if…else…语句在React渲染函数?

基本上,我有一个react组件,它的render()函数体如下所示:(这是我的理想,这意味着它目前不工作)

render(){
return (
<div>
<Element1/>
<Element2/>


// note: logic only, code does not work here
if (this.props.hasImage) <ElementWithImage/>
else <ElementWithoutImage/>


</div>
)
}
496324 次浏览

if else结构的简写在JSX中可以正常工作

this.props.hasImage ? <MyImage /> : <SomeotherElement>

你可以在DevNacho的这篇博客文章中找到其他选项,但更常见的是用简写来做。如果你需要一个更大的If子句,你应该写一个返回组件a的函数。

例如:

this.setState({overlayHovered: true});


renderComponentByState({overlayHovered}){
if(overlayHovered) {
return <OverlayHoveredComponent />
}else{
return <OverlayNotHoveredComponent />
}
}

你可以从中解构你的overlayhovers。状态,如果你给它作为参数。然后在render()方法中执行该函数:

renderComponentByState(this.state)

不完全是那样,但也有变通办法。在反应的文档中有一个关于条件呈现的部分,你应该看一看。下面是一个使用内联if-else的示例。

render() {
const isLoggedIn = this.state.isLoggedIn;
return (
<div>
{isLoggedIn ? (
<LogoutButton onClick={this.handleLogoutClick} />
) : (
<LoginButton onClick={this.handleLoginClick} />
)}
</div>
);
}

您也可以在渲染函数中处理它,但在返回jsx之前。

if (isLoggedIn) {
button = <LogoutButton onClick={this.handleLogoutClick} />;
} else {
button = <LoginButton onClick={this.handleLoginClick} />;
}


return (
<div>
<Greeting isLoggedIn={isLoggedIn} />
{button}
</div>
);

值得一提的是,ZekeDroid在评论中提到了这一点。如果你只是检查一个条件,不想呈现不符合条件的特定代码段,你可以使用&& operator

  return (
<div>
<h1>Hello!</h1>
{unreadMessages.length > 0 &&
<h2>
You have {unreadMessages.length} unread messages.
</h2>
}
</div>
);

也许我来晚了。但我希望这能帮助到一些人。首先分离这两个元素。

renderLogout(){
<div>
<LogoutButton onClick={this.handleLogoutClick} />
<div>
}


renderLogin(){
<div>
<LoginButton onClick={this.handleLoginClick} />
<div>
}

然后你可以使用if else语句从render function调用这些函数。

render(){
if(this.state.result){
return this.renderResult();
}else{
return this.renderQuiz();
}}

这对我很有用。:)

如果你需要不止一个条件,那么你可以试试这个

https://www.npmjs.com/package/react-if-elseif-else-render

import { If, Then, ElseIf, Else } from 'react-if-elseif-else-render';


class Example extends Component {


render() {
var i = 3; // it will render '<p>Else</p>'
return (
<If condition={i == 1}>
<Then>
<p>Then: 1</p>
</Then>
<ElseIf condition={i == 2}>
<p>ElseIf: 2</p>
</ElseIf>
<Else>
<p>Else</p>
</Else>
</If>
);
}
}

你可以使用conditional语句呈现任何东西,比如ifelse:

 render() {
const price = this.state.price;
let comp;


if (price) {


comp = <h1>Block for getting started with {this.state.price}</h1>


} else {


comp = <h1>Block for getting started.</h1>


}


return (
<div>
<div className="gettingStart">
{comp}
</div>
</div>
);
}

如果您想要一个条件来显示元素,您可以使用类似这样的东西。

renderButton() {
if (this.state.loading) {
return <Spinner size="small" spinnerStyle={styles.spinnerStyle} />;
}


return (
<Button onPress={this.onButtonPress.bind(this)}>
Log In
</Button>
);
}

然后调用渲染函数中的帮助方法。

<View style={styles.buttonStyle}>
{this.renderButton()}
</View>

或者你也可以用另一种方法在return中设置条件。

{this.props.hasImage ? <element1> : <element2>}

实际上有一种方法可以完全满足OP的要求。只需要像这样渲染和调用一个匿名函数:

render () {
return (
<div>
{(() => {
if (someCase) {
return (
<div>someCase</div>
)
} else if (otherCase) {
return (
<div>otherCase</div>
)
} else {
return (
<div>catch all</div>
)
}
})()}
</div>
)
}

你应该记住三元运算符

你的代码是这样的,

render(){
return (
<div>
<Element1/>
<Element2/>
// note: code does not work here
{
this.props.hasImage ?  // if has image
<MyImage />            // return My image tag
:
<OtherElement/>        // otherwise return other element


}
</div>
)
}

我用了一个三元运算符,它对我来说工作得很好。

{item.lotNum == null ? ('PDF'):(item.lotNum)}

如果你有2个不同的依赖关系,你也可以在条件操作符中使用条件(三元)操作符。

{
(launch_success)
?
<span className="bg-green-100">
Success
</span>
:
(upcoming)
?
<span className="bg-teal-100">
Upcoming
</span>
:
<span className="bg-red-100">
Failed
</span>
}

类型1: If语句样式

{props.hasImage &&


<MyImage />


}

< br >

类型2: If else语句样式

   {props.hasImage ?


<MyImage /> :


<OtherElement/>


}

尝试使用Switch case或三元操作符

render(){
return (
<div>
<Element1/>
<Element2/>
// updated code works here
{(() => {
switch (this.props.hasImage) {
case (this.props.hasImage):
return <MyImage />;
default:
return (
<OtherElement/>;
);
}
})()}
</div>
)
}
这对我有用,对你也应该有用。 尝试三元运算符 < / p >

如果你想使用If, else If和else则使用此方法

           {this.state.value === 0 ? (
<Component1 />
) : this.state.value === 1 ? (
<Component2 />
) : (
<Component3 />
)}


下面的代码,你可以使用的If条件反应在侧返回

                                    {(() => {if (true) {return ( <div><Form>
<Form.Group as={Row} style=\{\{ marginLeft: '15px', marginRight: '15px', marginBlock: '0px' }} >
<Form.Label className="summary-smmdfont" style=\{\{ flex: '1 0 auto', marginBlock: '0px' }}>   uyt</Form.Label>
<Form.Label className="summary-smmdfont"style=\{\{ textAlignLast: 'Right', flex: '1 0 auto', marginBlock: '0px' }}>
09</Form.Label>
</Form.Group>
</Form>


</div>);
}})()}

很多很棒的答案,但我还没有看到使用对象映射到不同的视图

const LOGS = {
info: <Info />,
warning: <Warning />,
error: <Error />,
};
 

const Notification = ({ status }) => <div>{LOGS[status]}</div>

没有一个答案提到短路法

{this.props.hasImage && <MyImage />}


当然,如果你想在else逻辑上呈现一些东西,你不能使用它。 我在通过例子做出反应

上了解到这个

在更深入的扫描中,我确实看到了@ZekeDroid的评论,但我将把它作为答案,因为它可能有用。

我找到了一个我认为比“如果-否则”更好的解决方案。应该使用2条return语句。看到的例子:

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


if (isLoggedIn) {
return <LogoutButton onClick={this.handleLogoutClick} />
}


// This will never occur if the user is logged in as the function is returned before that.
return <LoginButton onClick={this.handleLoginClick} />
}

这比在return语句中使用if-else或三元操作符更简洁。

你可以引入一个单独的方法来返回div元素并在return中调用它。我使用这种情况的例子,错误呈现取决于状态,如:

const renderError = () => {
if (condition)
return ....;
else if (condition)
return ....;
else if (condition)
return ....;
else
return ....;
}


render(){
return (
<div>
....
{renderError()}
</div>
);
}

四种条件渲染方式

(在功能组件的返回语句或类组件的渲染函数的返回语句中)

 

三元运算符

 

return (
<div>
{
'a'==='a' ? <p>Hi</p> : <p>Bye</p>
}
</div>
)

只有条件'a'==='a'为真,<p>Hi</p>才会显示在屏幕上。否则,<p>Bye</p>将呈现在屏幕上。

 

逻辑运算符

 

&&

return (
<div>
{
'a'==='a' && <p>Hi</p>
}
</div>
)

只有当条件'a'==='a'为真时,<p>Hi</p>才会在屏幕上显示。

 

||

export default function LogicalOperatorExample({name, labelText}) {
    

return (
<div>
{labelText || name}
</div>
)
}

注意:如果labelTextname两个道具都被传递到这个组件中,那么labelText将在屏幕中呈现。但如果只有一个(namelabelText)被作为道具传递,那么传递的道具将在屏幕上呈现。

 

如果,否则,否则如果

 

return (
<div>
{
(() => {
if('a'==='b') {
return (
<p>Hi</p>
)
} else if ('b'==='b') {
return (
<p>Hello</p>
)
} else {
return (
<p>Bye</p>
)
}
})()
}
</div>
)

注意:必须使用匿名函数(也需要立即调用该函数)

 

Switch语句

 

return (
<div>
{
(() => {
switch(true) {
                        

case('a'==='b'): {
return (
<p>Hello</p>
)
}
break;
                        

case('a'==='a'): {
return (
<p>Hi</p>
)
}
break;
                    

default: {
return (
<p>Bye</p>
)
}
break;
}
})()
}
</div>
)

注意:必须使用匿名函数(也需要立即调用该函数)

if then的简写

 { condition ? <Element1/> : null }

我不认为我看到这个解决方案的内联else if渲染,你有超过2个条件,所以我分享它:

{variable == 0 ?
<Element1/>
:variable == 1 ?
<Element2/>
:variable == 2 ?
<Element3/>
:
<Element4/>
}
< p >,如果[…Else if], Else 在React返回函数中检查不止一次?< / p >
{Element1? (<Element1/>) : Element2 ? (<Element2/>) : Element3 ? (<Element3/>) : Element... ? (<Element.../>) : (<ElementLast />)}

你也可以写If语句组件。这是我在我的项目中使用的。

组件/ IfStatement.tsx

import React from 'react'


const defaultProps = {
condition: undefined,
}


interface IfProps {
children: React.ReactNode
condition: any
}


interface StaticComponents {
Then: React.FC<{ children: any }>
Else: React.FC<{ children: any }>
}


export function If({ children, condition }: IfProps): any & StaticComponents {
if (React.Children.count(children) === 1) {
return condition ? children : null
}


return React.Children.map(children as any, (element: React.ReactElement) => {
const { type: Component }: any = element


if (condition) {
if (Component.type === 'then') {
return element
}
} else if (Component.type === 'else') {
return element
}


return null
})
}


If.defaultProps = defaultProps


export function Then({ children }: { children: any }) {
return children
}


Then.type = 'then'


export function Else({ children }: { children: any }) {
return children
}


Else.type = 'else'


If.Then = Then as React.FC<{ children: any }>
If.Else = Else as React.FC<{ children: any }>


export default If

使用的例子:

<If condition={true}>
<If.Then>
<div>TRUE</div>
</If.Then>
<If.Else>
<div>NOT TRUE</div>
</If.Else>
</If>

是的,你可以在JSX渲染中使用条件。你可以阅读更多在这里

语法:

condition ? exprIfTrue : exprIfFalse

条件声明必须如下所示,这里有一个例子:

return (
<div>
{condition  ? (
//do some actions if condition is true
) : (
//do some actions if condition is false
)}
</div>
)