在React中动态嵌套元素

时间:2018-04-16 17:18:24

标签: javascript reactjs

我是React的初学者,我希望尝试动态创建内容行和框的数量,具体取决于我可用的内容量,但创建行很容易,但由于某种原因,它不会似乎可以以相同的方式将盒子嵌入其中。这是我到目前为止尝试使用的代码示例:

编辑(澄清代码):



import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

const yAxis = ["y1", "y2", "y3", "y4", "y5"];
const xAxis = ["x1", "x2", "x3", "x4", "x5"];

const rows = yAxis.map((row) =>
  <div key={row.toString()} className={"boxrow " + row.toString()} >
    {boxes}
  </div>
);

const boxes = xAxis.map((box) =>
  <div key={box.toString()} className={"box " + box.toString()}>
    {box}
  </div>
);

class App extends Component {
  render() {
    return (
        <div className="rows">
          {rows}
        </div>
    );
  }
}

export default App; 
&#13;
&#13;
&#13;

我想知道的是,为什么我不能简单地在rows-method中嵌入box-method?我的印象是,这种东西正是React的设计目标。

编辑:

或者,我尝试了以下方法,只是因为它导致错误:

主要指数:

&#13;
&#13;
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import Boxes from './Boxes'; 
import Rows from './Rows';
import registerServiceWorker from './registerServiceWorker';

ReactDOM.render(<Rows />, document.getElementById('root'));

registerServiceWorker();
&#13;
&#13;
&#13;

箱:

&#13;
&#13;
import React, { Component } from 'react';

const xAxis = ["x1", "x2", "x3", "x4", "x5"];

class Boxes extends Component {
    boxes = xAxis.map((box) =>
        <div key={box.toString()} className="box ">
            {box}
        </div>
    );
}

export default Boxes; 
&#13;
&#13;
&#13;

行:

&#13;
&#13;
import React, { Component } from 'react';
import Boxes from './Boxes';

const yAxis = ["y1", "y2", "y3", "y4", "y5"];

class Rows extends Component {
    rows = yAxis.map((row) =>
        <div key={row.toString()} className="boxrow">
            <Boxes />
        </div>
    );

}

export default Rows; 
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

我认为这就是你想要制作的东西:

    const yAxis = ["y1", "y2", "y3", "y4", "y5"];
    const xAxis = ["x1", "x2", "x3", "x4", "x5"];

    class Box extends React.Component {
      render() {
        return (
          <div>{this.props.boxes.map((box) =>
            <div>{box}</div>
          )}</div>
        );
      }
    }

    class Row extends React.Component {
      render() {
        return (
          <div>{this.props.rows.map((row) =>
            <div>{<Box boxes={xAxis}/>}</div>
          )}</div>
        );
      }
    }

    class App extends React.Component {
      render() {
        return (
            <div className="rows">
              <Row rows={yAxis}/>
            </div>
        );
      }
    }

    ReactDOM.render(<App/>, document.body)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

我注意到的一件事是你的无状态组件结构不正确。他们应该返回一个组件。

其次,您应该尝试使用props