我刚刚开始学习 React,虽然我了解许多基础知识,但有一个概念我还没有看到任何人涉及:如何获取通过服务器端语言(例如 PHP)加载的信息并在何时使用它加载 React View ?
我本来希望在我的 php View 中调用 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
脚本区域没有被执行...但是当然如果我删除它就会出现语法错误。
Soo...我只是想知道,从数据库加载数据并将其传递到 React 组件的典型方法是什么?
最佳答案
方法一:定义一个全局变量。
在您的主 PHP 文件中:
<script>
window.reactInit = {
username: <?php echo $username; ?>
};
</script>
在你的组件中:
class Greeting extends React.Component {
constructor(props) {
super(props);
this.username = reactInit.username;
}
}
如果你使用 Redux,你可能会发现这个方法特别有用。因为您的任何 reducer 都可以在构建初始状态期间访问此全局变量。
方法二:使用data-*
属性。
<div id="app" data-username="<?php echo $username; ?>"></div>
所有 data-*
属性都使用 {...app.dataset}
传递。
const app = document.getElementById('app');
ReactDOM.render(<Greeting {...app.dataset} />, app);
现在您可以像普 channel 具一样访问您的服务器数据。
class Greeting extends React.Component {
constructor(props) {
super(props);
console.log(this.props.username);
}
}
这种方法没有前一种那么灵活,但似乎更符合 React 哲学。
关于php - 如何将服务器数据传递给 React 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40370109/