如何使用一个组件在reactjs中渲染许多html片段?

时间:2014-07-08 08:29:25

标签: javascript html reactjs

我有一个按钮,当我点击此按钮时,我想渲染div并将其附加到body

当我再次点击此按钮时,会呈现新的div

我想要:我点击按钮的次数,要渲染的div

以下代码只能呈现一个div :( jsFiddle:http://jsfiddle.net/pw4yq/

var $tool = document.getElementById('tool');
var $main = document.getElementById('main');

var partBox = React.createClass({displayName: 'partBox',
    render: function(){
        return (
            React.DOM.div({className:"box"}, "HELLO! ", this.props.ts)
        )
    }
});

var createBoxBtn = React.createClass({displayName: 'createBoxBtn',

    createBox: function(){
        var timeStamp = new Date().getTime();
        React.renderComponent(partBox( {ts:timeStamp} ), $main);
    },

    render: function(){
        return (
            React.DOM.button( {onClick:this.createBox}, "createBox")
        )
    }
});

React.renderComponent(createBoxBtn(null ), $tool);

1 个答案:

答案 0 :(得分:5)

您的应用应该是数据驱动的,这意味着您的应用状态保持在DOM之外。在您的示例中,您实际上是保留Date对象的列表。将其置于您可以修改的状态,并为您创建的每个Date对象渲染一个框:

使用JSFiddle:http://jsfiddle.net/pw4yq/6/

var $main = document.getElementById('main');

var partBox = React.createClass({displayName: 'partBox',
    render: function(){
        return (
            React.DOM.div({className:"box"}, "HELLO! ", this.props.ts)
        )
    }
});

var createBoxBtn = React.createClass({displayName: 'createBoxBtn',

    createBox: function(){
        var timeStamp = new Date().getTime();
        this.props.onClick({ts: timeStamp});
    },

    render: function(){
        return (
            React.DOM.button({onClick: this.createBox}, "createBox")
        )
    }
});

var app = React.createClass({
    displayName: "app",

    getInitialState: function() {
        return {
            partBoxes: []
        };
    },

    createBox: function(partBox) {
        this.state.partBoxes.push(partBox);
        this.forceUpdate();
    },

    render: function() {
        return (
            React.DOM.div(null,
                createBoxBtn({onClick: this.createBox}),
                this.state.partBoxes.map(function(pb) {
                    return partBox({key: pb.ts, ts: pb.ts});
                })
            )
        );
    }
});


React.renderComponent(app(null), $main);