动态创建 React 元素

Create React element dynamically

我正在用 ReactJS(有点像 Facebook)进行聊天,我用 ReactJS 创建了 ChatBox,所以每当你点击一个在线用户时,都必须创建一个 ChatBox,我的问题是,是否有创建一个 ReactJS 组件可能会动态地将 ChatBox 添加到 div 或另一个 React 元素?

这是我的代码:https://gist.github.com/victorcastillo/2c6cb3af4650729eaa1f

最简单的方法是让您的容器存储一个聊天框列表,您可以在其中添加或删除聊天框,具体取决于它们是打开还是关闭。

var ChatBox = React.createClass({
    render: function () {
        return <div>a new chatbox!</div>;
    }
});

var Container = React.createClass({
    getInitialState: function () {
        return { chatboxes: [] };
    },
    renderChatbox: function () {
        var cbs = this.state.chatboxes;
        cbs.push(<ChatBox />);
        this.setState({chatboxes: cbs});
    },
    render: function() {
        return <div>Hello, do you want to open a chatbox <a onClick={this.renderChatbox}>click here</a>
        {this.state.chatboxes}
        </div>;
    }
});

React.render(<Container name="World" />, document.body);

稍微扩展一下答案并假设您没有使用 Flux 模式,那么为了让容器知道 ChatBox 已关闭,您必须将回调从容器传递到每个 ChatBox。

so whenever you click on an online user a ChatBox has to be created

当用户单击在线用户字形时,这应该会触发状态更改——您将跟踪打开的聊天 windows。状态变化会触发一个React.render循环。在您的呈现函数中,您必须根据打开的聊天数量(状态变量)来决定如何以及在何处调用和放置您的聊天 windows。这些本身应该是 React 组件,您将 pass/inject 函数和 Id 作为道具放入其中。

这就是没有代码示例的答案。希望对你有帮助。

是的,你可以。对于 div,您只需执行通常的

React.render(
    <ChatBox />,
    document.getElementById('content')
);

您可以传递反应 class 定义(即 ChatBox 变量)或 react factory in a property. You can later generate an instance of that component and add it somewhere in your view. The easiest way to add it to the view is to change the children of a Container type of component

codepen 示例(es6 语法)