如何渲染未知/可变数量的React元素

时间:2015-12-28 20:13:06

标签: javascript reactjs

我有这个React组件,如下所示:

 var TestResult = React.createFactory(React.createClass({

        displayName: 'test-result',

        getInitialState: function getInitialState() {
            return {
                active: false,
                testLines: []  //this value will update after AJAX/WebWorker completes
            };
        },

        makeNewState: function makeState(data) {
            this.setState(data);
        },

        componentDidMount: function () {

            var self = this;
            var testPath = this.props.testPath;

            setTimeout(function(){
                $.get(testPath).done(function (msg) {

                    var myWorker = new Worker('/js/workers/one.js');
                    myWorker.postMessage(msg);
                    myWorker.onmessage = function (msg) {

                        self.setState({testLines: msg.data.testLines});

                    };

                }).fail(function (err) {
                    console.error(err);
                });
            }, Math.random()*2000);

        },

        render: function() {

            var self = this;

            return React.createElement('p', {
                    className: this.state.active ? 'active' : '',
                    onClick: this.clickHandler,
                },
                self.state.testName, '  ', self.state.testLines, React.createElement('b', null, 'Pass/fail')
            );
        }

    }));

我想要的是在渲染函数中渲染可变数量的组件 - 变量号与testLines数组中的元素数量相关。

所以,为了做到这一点,我可能会尝试更改上面的渲染方法:

 render: function() {

            var self = this;

            return React.createElement('p', {
                    className: this.state.active ? 'active' : '',
                },
                self.state.testName, '  ', React.createElement('div', self.state.testLines, React.createElement('b', null, 'Pass/fail')
            );
        }

所以我要做的是将testLines(一个React.createElement结果数组)传递给React.createElement。这是正确的做法吗? “它”意味着渲染可变数量的React元素。

1 个答案:

答案 0 :(得分:4)

您需要做的是映射数组并创建每个子元素,然后渲染它们:

render: function() {
  var lines = this.state.testLines.map(function(line, i) {
    // This is just an example - your return will pull information from `line`
    // Make sure to always pass a `key` prop when working with dynamic children: https://facebook.github.io/react/docs/multiple-components.html#dynamic-children
    return (
      <div key={i}>I am a line!</div>
    );
  });

  return (
    <div id='lineContainer'>
      {lines}
    </div>
  );
};