Я пытаюсь динамически генерировать компоненты предупреждений в 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>