我只是在学习React,虽然我了解很多基础知识,但有一个概念我还没见过有人讲过:如何获取通过服务器端语言(例如PHP)加载的信息,并在加载React视图时使用它?
我希望在我的php视图中只有RenderDom
调用,比如:
// In the pre-compiled JSX file
var Greeting = React.createClass({
render: function() {
<div>
<h1>Hello, { this.props.username }</h1>
</div>
}
});
// In my PHP view
<script type="text/jsx">
ReactDOM.render( <Greeting username="<?php echo $username; ?>"/>, document.body );
</script>
但这不起作用;没有显示任何内容。我想这是因为text/jsx
脚本区域没有得到executed...but,当然,如果我去掉它,就会有一个语法错误。
所以……我想知道,从DB加载数据并将其传递到React组件的典型方法是什么?
发布于 2016-11-02 07:57:45
React的方式是通过RESTful应用程序接口加载数据。
但是,您可以查看serverside rendering of React components with PHP V8JS。不确定它有多稳定,但如果是的话,它将是一个非常好的/更好的替代客户端的AJAX调用。它看起来有点像这样:
// the library
$react_source = file_get_contents('/path/to/build/react.js');
// all custom code concatenated
$app_source = file_get_contents('/path/to/custom/components.js');
$rjs = new ReactJS($react_source, $app_source);
$rjs->setComponent('MyComponent', array(
'any' => 1,
'props' => 2
)
);
/// ...
// print rendered markup
echo '<div id="here">' . $rjs->getMarkup() . '</div>';
如果你真的想在浏览器中呈现它,你可以使用普通的Javascript而不是JSX:
<?php $username = 'Eric Andre'; ?>
<script type="text/javascript">
ReactDOM.render(React.createElement(Greeting, { username: "<?php echo $username; ?>" }), document.body);
</script>
另一种选择是使用babel-browser并使用<script type="text/babel">
将JSX转换为普通的Javascript。请记住,babel-browser不再处于活跃的开发阶段,也不打算用于生产。
<?php $username = 'Eric Andre'; ?>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/6.1.19/browser.min.js"></script>
<script type="text/babel">
ReactDOM.render( <Greeting username="<?php echo $username; ?>"/>, document.body );
</script>
发布于 2016-11-03 13:50:28
您还可以查看https://github.com/erikras/react-redux-universal-hot-example,获取有关如何从客户端调用RESTful API的示例。
具体地说,它使用superagent进行AJAX调用:https://github.com/visionmedia/superagent
https://stackoverflow.com/questions/40370109
复制相似问题