Динамическое создание компонентов в React-Bootstrap

Я пытаюсь динамически генерировать компоненты предупреждений в React-Bootstrap во время выполнения, создавая экземпляры компонентов из классов Javascript. Я делаю это, потому что есть много предупреждений, которые нужно показать, и потому что классы Javascript проще создавать.

Мои попытки сделать это не работают. Я не уверен, относится ли проблема вообще к React или только к React-Bootstrap. Однако ошибка возникает в react.js, которая выдает следующее:

TypeError: undefined is not a function

Бросок происходит в вызове alert.getComponent() в следующем файле JSX:

/** @jsx React.DOM */

var Alert = ReactBootstrap.Alert;

var AlertDismissible = React.createClass({
    getInitialState: function() {
        return {
            isVisible: true
        };
    },

    render: function() {
        if(!this.state.isVisible)
            return null;

        var message = this.props.message;
        if(this.props.code !== null)
            message = message +'(Code '+ this.props.code +')';
        return (
            <Alert bsStyle={this.props.level} onDismiss={this.dismissAlert}>
                <p>{message}</p>
            </Alert>
        );
    },

    dismissAlert: function() {
        this.setState({isVisible: false});
    }
});

function AlertNotice(level, message, code) {
    this.level = level;
    this.message = message;
    this.code = code || null;
}

AlertNotice.prototype.getComponent = function() {
    // What should go here? Using React.createClass() doesn't help
    return (
        <AlertDismissible level={this.level} message={this.message}
                code={this.code} />
    );
};

function SuccessAlert(message) {
    AlertNotice.call(this, 'success', message);
}
SuccessAlert.prototype = Object.create(AlertNotice);
SuccessAlert.prototype.constructor = SuccessAlert;

/* ...more kinds of alerts... */

function ErrorAlert(message, code) {
    AlertNotice.call(this, 'danger', message, code);
}
ErrorAlert.prototype = Object.create(AlertNotice);
ErrorAlert.prototype.constructor = ErrorAlert;

var SomethingWithAlerts = React.createClass({
    render: function() {
        var alerts = [
            new ErrorAlert("Goof #1", 123),
            new ErrorAlert("Goof #2", 321)
        ].map(function(alert) {
            // react.js throws "TypeError: undefined is not a function"
            return alert.getComponent();
        });
        return (
            <div>{alerts}</div>
        );
    }
});

var TestComponent = (
    <div>
        <SomethingWithAlerts />
    </div>
);

React.renderComponent(
  TestComponent,
  document.getElementById('content')
);

Компонент Alert взят из библиотеки React-Bootstrap. Компоненты div кажутся посторонними, но я нашел их необходимыми для соответствия структуре реагирования. На самом деле я буду хранить AlertNotice экземпляров в состоянии реакции, а затем генерировать из них узлы реакции.

Каков правильный способ сделать это?

Вот подсказка. Если я заменю return alert.getComponent(); следующим жестко запрограммированным предупреждением, компоненты AlertDismissible отобразятся без ошибок (в двух экземплярах), но я получу предупреждение:

return (
    <AlertDismissible level="danger" message="Goof" code="777" />
);

Ниже приведено предупреждающее сообщение, которое я получаю с вышеуказанной заменой, включая ссылку, которая объясняет, что я должен установить key= уникальным для каждого предупреждения:

Each child in an array should have a unique "key" prop. Check the render method
of SpecimenSetManager. See http://fb.me/react-warning-keys for more information.

Однако, если я просто заменю код внутри AlertNotice.prototype.getComponent вышеприведенным жестко заданным предупреждением, я получу то же сообщение TypeError, что и раньше.

Для полноты, вот мой исходный код HTML. Это реакция и реакция-ускорение v0.11.1

<html>
  <head>
    <script src="lib/react.js"></script>
    <script src="lib/react-bootstrap.js"></script>
    <script src="lib/JSXTransformer.js"></script>
    <link rel="stylesheet" href="css/bootstrap-theme.min.css">
    <link rel="stylesheet" href="css/bootstrap.min.css">
  </head>
  <body>
    <div id="content"></div>
    <script src="components.js" type="text/jsx"></script>
  </body>
</html>

person Joe Lapp    schedule 05.08.2014    source источник


Ответы (1)


Я решил проблему. Решение состояло в том, чтобы создать специальный компонент реагирования, который представляет собой набор предупреждений. По-видимому, в параметрах компонента можно ссылаться только на автоматические или объектные переменные из определения React.createClass(). Возможно, это синтаксическое ограничение JSX, а не логическое ограничение реакции.

Я не понимаю, почему это решение работает. Я хотел бы понять, чтобы мне не пришлось снова сталкиваться с подобными проблемами в будущем. Если вы сможете объяснить общий принцип, который я нарушаю, и общий принцип, которому вместо этого следует следовать — что-то более проницательное, чем то, что я изложил здесь, — тогда я отмечу ваш ответ как «ответ» на этот вопрос. Я хотел бы знать, насколько гибкой я действительно обладаю.

Вот работающий код, включая новый компонент AlertSet:

/** @jsx React.DOM */

function AlertNotice(level, message, code) {
    this.level = level;
    this.message = message;
    this.code = code || null;
}

function SuccessAlert(message) {
    AlertNotice.call(this, 'success', message);
}
SuccessAlert.prototype = Object.create(AlertNotice);
SuccessAlert.prototype.constructor = SuccessAlert;

/* ...more kinds of alerts... */

function ErrorAlert(message, code) {
    AlertNotice.call(this, 'danger', message, code);
}
ErrorAlert.prototype = Object.create(AlertNotice);
ErrorAlert.prototype.constructor = ErrorAlert;

var Alert = ReactBootstrap.Alert;

var AlertDismissible = React.createClass({
    getInitialState: function() {
        return {
            isVisible: true
        };
    },

    render: function() {
        if(!this.state.isVisible)
            return null;

        var message = this.props.message;
        if(this.props.code !== null)
            message = message +'(Code '+ this.props.code +')';
        return (
            <Alert bsStyle={this.props.level} onDismiss={this.dismissAlert}>
                <p>{message}</p>
            </Alert>
        );
    },

    dismissAlert: function() {
        this.setState({isVisible: false});
    }
});

var AlertSet = React.createClass({
    render: function() {
        var alerts = this.props.alerts.map(function(alert, i) {
            return (
                <AlertDismissible key={"alert-"+i} level={alert.level}
                        message={alert.message} code={alert.code} />
            );
        });
        // component must be a single node, so wrap in a div
        return (
            <div>{alerts}</div>
        );
    }
});

var SomethingWithAlerts = React.createClass({
    render: function() {
        var alerts = [
            new ErrorAlert("Goof #1", 123),
            new ErrorAlert("Goof #2", 321)
        ];
        return (
            <AlertSet alerts={alerts} />
        );
    }
});

// TestComponent returns a single node, so doesn't need a div
var TestComponent = (
    <SomethingWithAlerts />
);

React.renderComponent(
  TestComponent,
  document.getElementById('content')
);
person Joe Lapp    schedule 05.08.2014