React:从函数内渲染组件

时间:2015-07-03 10:22:41

标签: javascript reactjs

有没有办法让以下工作?我想通过" welcome"以onClick事件为例,它应该将具有该名称的组件呈现给指定的DIV。我希望它被动态命名,但我可以满足于switch(索引):)

var Menu = React.createClass({
    getInitialState: function() {
        return {data: []};
    },
    componentDidMount: function() {
        // do something
    },
    menuClick: function(index) {
        render(
            <{index} />,
            document.getElementById('content')
        );
    },
    render: function() {
        return (
            <span>
                <span className="menuLink" onClick={this.menuClick.bind(this, "welcome")}>Home</span>&nbsp;
                <span className="menuLink" onClick={this.menuClick.bind(this, "management")} >Generator Management</span>&nbsp;
                <span className="menuLink" onClick={this.menuClick.bind(this, "about")}>About Us</span>
            </span>
        );
    }
});

3 个答案:

答案 0 :(得分:0)

在这种情况下,你可以选择使用JSX:

menuClick: function(index) {
        render(
            React.createElement(index, null, ''),
            document.getElementById('content')
        );
    },

答案 1 :(得分:0)

您可以使用组件的state来执行此操作

    var Menu = React.createClass({
      getInitialState: function() {
        return {
          data: [],
          message: null
        };
      },
      componentDidMount: function() {
        // do something
      },
      menuClick: function(index) {
        this.setState({
          message: index
        });
      },

      getText: function() {
        if (this.state.message) {
          return (
            <h1>{this.state.message}</h1>
          );
        }
        return null;
      }

      render: function() {
        return (
          <div>
            <span>
              <span className="menuLink" onClick={this.menuClick.bind(this, "welcome")}>Home</span>&nbsp;
              <span className="menuLink" onClick={this.menuClick.bind(this, "management")} >Generator Management</span>&nbsp;
              <span className="menuLink" onClick={this.menuClick.bind(this, "about")}>About Us</span>
            </span>
            {this.getText()}
          </div>
        );
      }
    });

答案 2 :(得分:0)

为什么不使用react-router,它专门用于这些目的。