【问题标题】:How to add className to list from map array depending on object value如何根据对象值将类名添加到地图数组中的列表
【发布时间】: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


【解决方案1】:

你可以像这样使用一个简单的函数:

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>
        )

【讨论】:

  • 优秀。一个正确的答案。谢谢。我很努力地在代码中获取这个逻辑,但那是错误的。您的解决方案简单但有效 - 我希望我能想到它!
  • 如果您想要更短的代码,您可以直接在 className 属性中使用三元运算符,如下所示: className = {(item.name === 'you' ? 'left' : 'right ')}
  • 那就更好了。谢谢。
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

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

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

    或者你可以这样做

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

    【讨论】:

    • 但列表将有一个非此即彼的,这取决于屏幕上正在打印的对象内的“名称”的值
    • 那么您可以在将其应用到组件之前创建该类数组。
    • 但这仍然留下了将 if 语句放在哪里的问题,或者如何将两个潜在类之一分配给动态生成的列表元素。怎么样?
    • 创建一个函数,该函数将根据您的逻辑返回类 ses 列表。 Reac.addons.classSet(yourFunction(params))
    【解决方案4】:

    在 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。

    【讨论】:

      猜你喜欢
      • 2016-07-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-25
      • 2021-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多