【发布时间】:2020-03-09 01:41:23
【问题描述】:
我正在尝试将 className 值添加到列表项。我映射了一个对象数组,根据对象中“name”的值,将添加一个不同的类。
具体来说,我正在尝试制作一个消息应用程序,如果用户是“你”,则消息将具有“正确”类,并且消息显示在屏幕的右侧。如果用户名 != 'You',则应给出 className 'left'。
我尝试在代码的渲染部分以及 sendMessage() 函数中添加一个 if 语句,以便在将消息推送到数组时添加类(甚至在它显示在屏幕上之前)。我得到的只是语法错误。请指教...
import React, { Component } from 'react';
class LandingPage extends Component {
constructor(props) {
// When you pass props to super, the props get assigned to 'this'
super(props);
// this.state is the buildiing block of the data that gets used
this.state = {
message: '',
name: '',
list: []
}
}
updateInput(key, value) {
// update react state with input data
this.setState({
[key]: value
})
}
sendMessage() {
const newMessage = {
message: this.state.newMessage,
name: 'You'
}
const list = [...this.state.list];
list.push(newMessage);
this.setState({
list,
newMessage: ''
})
}
render() {
return <div className='container'>
{/* messages will be listed here */}
<div className='messagesDiv'>
<ul>
{/* List array is mapped through*/}
{this.state.list.map(item => {
return (
<li className={item.class}>
{item.name}: {item.message}
</li>
)
})}
</ul>
</div>
{/* message text area and send button here */}
<div className='inputDiv'>
<form>
<input type='text' className='input'
value={this.message}
onChange={e => this.updateInput('newMessage', e.target.value)}
/>
<button className='btn btn-primary'
onClick={() => this.sendMessage()}>Send</button>
</form>
</div>
</div>
}
}
export default LandingPage;
所以在它有 {item.class} 的地方,它应该是“右”或“左”。
我只留下了我认为您需要查看以诊断我的问题/提供解决方案的代码。
谢谢。
【问题讨论】:
-
你得到了哪些语法错误,在哪个位置?
-
我尝试在组件的“返回”和 sendMessage 函数中添加一个 if 语句。我在代码中得到了红线,包括检测到无法访问的代码的消息、预期的表达式等。没有什么会崩溃或阻止本地服务器上的应用程序编译,但没有积极的结果。
标签: reactjs dictionary object classname