如何根据对象值将类名添加到地图数组列表

How to add className to list from map array depending on object value

我正在尝试将 className 值添加到列表项中。我映射了一个对象数组,根据对象中 'name' 的值,将添加一个不同的 class。

具体来说,我正在尝试制作一个消息应用程序,如果用户是 'You',消息将具有 class 'right' 并且消息显示在屏幕。如果用户名 != 'You',则应给出 class 名称 'left'。

我尝试在代码的渲染部分添加一个 if 语句,也在 sendMessage() 函数中添加 class 将消息推入数组时(甚至在显示之前)屏幕上)。我得到的只是语法错误。请指教...

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} 的上方,这应该是 'right' 或 'left'。

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

谢谢。

假设您有一组 类 从您的业务逻辑中派生出来的,在这种情况下,它非常简单。

<MyComponent className={React.addons.classSet(classes)} />;

或者你可以

 <MyComponent className={classNames.join(' ')} />;

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

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

   return userClass ;
}

然后像这样使用它:

return (
          <li className={userToClass(item.name)}>
            {item.name}: {item.message}
          </li>
        )

只需添加一个简单的三元运算符即可。看看下面的例子 -

{this.state.list.map(item => {
  return (
    <li className={item.name === 'You' ? 'float-left' : 'float-right'}>
      {item.name}: {item.message}
    </li>
  )
})}

在 NextJs 中你可以这样尝试:

{popup_links.map((link, i) =>(
            <a
              key={link.title + i}
              href={link.href}
              className={`${styles.button} ${styles[link.customClassName]}`}
              onClick={(e) => {
                // your data
              }}
            >
              {link.title}
            </a>
          ))}

link.customClassName 是您从 json 自定义的 class。