如何在 React 中使用 props 渲染 DOM?

How to render DOM using props in React?

实施并 export 一个新的 React 组件 TableHeader,它将代表 any 的标题行 table。这个 class 应该期望一个叫做 colsprop 是一个 array 的列名(作为字符串). class 应呈现包含 <tr>(table 行)的 <thead>(table head)元素。 <tr> 内部应该是一组 <th>(table 标题)元素,每个元素对应 cols prop.

中的每个字符串

使用 .map() 函数将 cols 属性转换为 <th> DOM 元素的数组(使用 JSX 和 内联表达式),然后将此数组包含在返回的 DOM 元素中。

一定要给每个 <th> 元素一个 key 属性(列名字符串是一个很好的值),以便 React 可以跟踪它。

在由 SenatorTable class 呈现的 DOM 中包含 TableHeader class 的实例(作为 child <table>). SenatorTable class 应该传递 TableHeader 它创建一个 cols 道具,即数组 ['Name', 'State', 'Phone', 'Twitter'].

这应该会导致标题行出现在 table 中(具有正确的 4 列)。

然而,这是我已经尝试过的;我不明白我是如何使用道具并使其正确渲染的。

export class TableHeader extends Component {
  render() {
    let colItems = this.props.cols.map((colName) => {
      return <th message={colName} key={colName}/>;
    });

    return (
      <thead>
        <tr>
          {colItems}
        </tr>
      </thead>
    )
  }
}

th 标签没有消息属性。

您需要将列名称包裹在开始和结束 th 标记中

 let colItems = this.props.cols.map((colName) => {
      return <th key={colName}>{colName}</th>;
    });