首页 > 解决方案 > 未创建 React.js 组件

问题描述

我有一组我想在表格中显示的对象。我有以下代码

class Table extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: this.props.data
    };
  }

  render() {
    return (
      <table>
          {this.state.data.map(row => {
            console.log(row);
            <Test/>
          })}
      </table>
    );
  }
}

class Test extends React.Component {
  constructor(props) {
    super(props);
    console.log("7");
  }

  render() {
    return;
  }
}

中的console.log()正确打印出我的所有数据,但是,我的Test构造函数中的console.log()从不打印。 为什么没有创建测试?


我的正确行如下:

class Rows extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: this.props.rowData
    };

    console.log("2");
  }

  render() {
    return (
      <tr>
        <td>{this.state.data.paymentFrom}</td>
        <td>{this.state.data.paymentTo}</td>
        <td>{this.state.data.paymentPeriod}</td>
        <td>{this.state.data.paymentAmount}</td>
      </tr>
    );
  }
}

标签: javascriptreactjs

解决方案


要正确渲染 Test 组件,您必须返回该组件,如果它永远不会在函数体上返回,则永远不会打印。

试试这个方法:

class Table extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: this.props.data
    };
  }

  render() {
    return (
      <table>
          {this.state.data.map(row => {
            console.log(row);

            return (<Test/>)
          })}
      </table>
    );
  }
}

class Test extends React.Component {
  constructor(props) {
    super(props);
    console.log("7");
  }

  render() {
    return;
  }
}

推荐阅读