You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中实现表格无数据时显示「无联系人」提示

解决联系人列表为空时显示提示的问题

嘿,我明白你遇到的问题啦~你之前尝试用{noEntries No entries}的写法不符合JSX语法规范,所以才会报错。咱们得用React支持的条件渲染语法来实现这个需求,下面是具体的修改方案:

步骤1:添加空状态判断

在render函数里,先判断传入的联系人数组是否为空:

const hasNoEntries = contactEntries.length === 0;

步骤2:修改tbody的渲染逻辑

把原来的{listItems}替换成条件渲染,当数组为空时显示提示行,否则渲染联系人列表。这里用三元表达式逻辑更清晰:

<tbody>
  {hasNoEntries ? (
    <tr>
      <td colSpan="4" style={{ textAlign: 'center', padding: '1rem' }}>No contacts</td>
    </tr>
  ) : (
    listItems
  )}
</tbody>

用colSpan="4"是因为你的表格实际有4列(包括删除按钮列),这样提示文本能跨列居中显示,视觉效果更协调。

完整修改后的组件代码

class ContactList extends Component {
  constructor(props) {
    super(props);
    this.createContact = this.createContact.bind(this);
  }

  delete(key) {
    this.props.delete(key);
  }

  createContact(item) {
    return (
      <tr key={item.key}>
        <td>{item.firstname}</td>
        <td>{item.lastname}</td>
        <td>{item.phone}</td>
        <td>
          <i
            className="fas fa-trash-alt"
            onClick={() => {
              if (window.confirm('Are you sure you want to delete ' + item.firstname + ' ' + item.lastname + ' from your contacts?'))
                this.delete(item.key)
            }}
          ></i>
        </td>
      </tr>
    )
  }

  render() {
    const contactEntries = this.props.entries;
    const listItems = contactEntries.map(this.createContact);
    // 添加空状态判断
    const hasNoEntries = contactEntries.length === 0;

    return (
      <table className="mui-table mui-table--bordered">
        <thead>
          <tr>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Phone</th>
          </tr>
        </thead>
        <tbody>
          {/* 条件渲染空状态提示 */}
          {hasNoEntries ? (
            <tr>
              <td colSpan="4" style={{ textAlign: 'center', padding: '1rem' }}>No contacts</td>
            </tr>
          ) : (
            listItems
          )}
        </tbody>
      </table>
    );
  }
};

export default ContactList;

为什么之前的写法报错?

JSX要求花括号里必须是合法的JavaScript表达式,{noEntries No entries}这种写法不符合语法规则。你需要用逻辑运算符(比如&&)或者三元表达式来实现条件渲染,明确告诉React什么时候渲染提示文本,什么时候渲染列表项。

内容的提问来源于stack exchange,提问作者Matt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:36:49