在React中,我如何在渲染中使用条件
In React how do I use a conditional with rendering?
我有一个简单的通知窗口,当接受/拒绝通知时,我会从notifications
数组中删除对象。
这是我处理显示消息的代码:
render: function() {
return (
<div className="chatwindowheight">
<div className="row">
<div className="large-12 columns">
<div className="large-8 columns">
<p className="thin partyHeader">Party <i className="fa fa-minus-square-o"></i></p>
</div>
<div className="large-4 columns">
<i className="fa fa-users pull-right"></i>
</div>
</div>
</div>
<div className="row chatwindowheight">
<div className="large-12 small-12 columns chatwindow" id="scrolldown">
<br/>
{
this.state.messages.map((message, i) => {
return (
<MessageComponent key={i}
username={message.username}
message={message.message}
whos={message.classed} />
);
})
}
</div>
</div>
<ChatSendComponent onChatSubmit={this.handleChatSubmit}/>
</div>
)
}
我想要的是像一样的东西
if (this.state.messages.length === 0) {
return (
<p>You have no new notifications.</p>
)
}
但当我试图将类似的东西包裹在当前循环中时,它告诉我if
是一个错误。React的新手,所以只是想了解处理这个问题的最佳方法。谢谢
有一些不同的方法可以解决您的问题:1.
{ this.state.messages.length > 0 ?
this.state.messages.map((message, i) => {
return (
<MessageComponent key={i}
username={message.username}
message={message.message}
whos={message.classed} />
);
}) : 'You have messages'
}
- 移除映射到渲染函数并在那里准备数据:
function render() { var message=''; if (this.state.messages.length) { } } <b>{message}</b>
相关文章:
- 有条件地与react路由器链接
- 如何使用React JS中的循环,根据条件渲染或不渲染表数据
- 在 React JSX 中有条件地呈现组件部分
- React.js 中的条件加载
- 在 React.js 中有条件地设置 html 属性
- React 模块内部的条件
- React Components 类名中的三元条件
- 我如何有条件地在 React 中的某些 HTML 中间包含一个标签
- 在React中,我如何在渲染中使用条件
- React中HTML元素的条件渲染
- 在React Router中基于slug的条件处理器
- 在React中有条件地渲染还是有条件地添加一个类来隐藏元素?
- 基于父CSS状态的条件子动画(带有React的样式组件)
- 如何有条件地添加属性到react DOM元素
- 使用条件时不显示React组件
- 为什么if-else条件在react jsx中使用时不起作用
- React Native条件不能工作
- React componentDidMount()中使用条件计时器间隔不起作用
- 仅当react.js中的条件为true时才发送道具
- 如何有条件地加载我的React组件