Ответ 1
Вот шаблон для разделения шаблона jsx, который использует модули CommonJS в NodeJS, Browserify или Webpack. В NodeJS я нашел модуль node -jsx полезным, чтобы избежать необходимости компиляции JSX.
// index.js
require('node-jsx').install({extension: '.jsx'});
var React = require('react'),
Component = require('./your-component');
// your-component.jsx
var YourComponent,
React = require('react'),
template = require('./templates/your-component.jsx');
module.exports = YourComponent = React.createClass({
render: function() {
return template.call(this);
}
});
// templates/your-component.jsx
/** @jsx React.DOM */
var React = require('react');
module.exports = function() {
return (
<div>
Your template content.
</div>
);
};
Обновление 2015-1-30: включено предложение в Damon Smith ответить на установку this
в функции шаблона для компонента React.
Обновление 12/2016: актуальная практика заключается в использовании расширения .js и использовании инструмента построения, такого как Babel, для вывода финального javascript из вашего источника. Посмотрите create-react-app, если вы только начинаете. Кроме того, последние рекомендации React рекомендуют разделение между компонентами, которые управляют состоянием (обычно называемыми "компонентами контейнера" ), и компонентами, которые являются презентационными. Эти составные компоненты теперь могут быть записаны как функции, поэтому они не за горами от функции шаблона, использованной в предыдущем примере. Вот как я бы рекомендовал отключить большую часть современного JSX-кода. Эти примеры по-прежнему используют синтаксис ES5 React.createClass()
.
// index.js
var React = require('react'),
ReactDOM = require('react-dom'),
YourComponent = require('./your-component');
ReactDOM.render(
React.createElement(YourComponent, {}, null),
document.getElementById('root')
);
// your-component.js
var React = require('react'),
YourComponentTemplate = require('./templates/your-component');
var YourComponentContainer = React.createClass({
getInitialState: function() {
return {
color: 'green'
};
},
toggleColor: function() {
this.setState({
color: this.state.color === 'green' ? 'blue' : 'green'
});
},
render: function() {
var componentProps = {
color: this.state.color,
onClick: this.toggleColor
};
return <YourComponentTemplate {...componentProps} />;
}
});
module.exports = YourComponentContainer;
// templates/your-component.js
var React = require('react');
module.exports = function YourComponentTemplate(props) {
return (
<div style={{color: props.color}} onClick={props.onClick}>
Your template content.
</div>
);
};