我有这个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') ); } }));
我想要的是在render函数中渲染可变数量的组件-可变数量与testLines数组中的元素数量有关。
因此,为了做到这一点,我可以尝试更改上面的render方法:
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元素。
您要做的是在数组上映射并创建每个子元素,然后渲染这些子元素:
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 (I am a line!); }); return ({lines}); };