如何根据对象值将 className 添加到映射数组中的列表

jes*_*lks 5 dictionary object classname reactjs

我正在尝试将 className 值添加到列表项。我映射对象数组,并根据对象中“名称”的值,添加不同的类。

具体来说,我正在尝试制作一个消息应用程序,如果用户是“您”,则该消息将具有“正确”类,并且该消息显示在屏幕的右侧。如果用户名 != '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;
Run Code Online (Sandbox Code Playgroud)

因此,在具有 {item.class} 的上方,它应该是“右”或“左”。

我只留下了我认为您需要查看来诊断我的问题/提供解决方案的代码。

谢谢。

小智 3

您可以使用像这样的简单函数:

function userToClass(user){
   var userClass = '';
   if(user === 'You') {
      userClass = 'left';
   }
   else 
      userClass = 'right';
   }

   return userClass ;
}
Run Code Online (Sandbox Code Playgroud)

然后像这样使用它:

return (
          <li className={userToClass(item.name)}>
            {item.name}: {item.message}
          </li>
        )
Run Code Online (Sandbox Code Playgroud)