如何将服务器数据传递到React组件

时间:2016-11-01 23:20:11

标签: php reactjs

我刚刚学习了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脚本区域没有被执行...但当然如果我删除它会出现语法错误。

Soo ......我只是想知道,从数据库加载数据并将其传递到React组件的典型方法是什么?

3 个答案:

答案 0 :(得分:3)

React的方式是通过RESTful API加载数据。

但是,您可以查看serverside rendering of React components with PHP V8JS。不确定它有多稳定,但如果它是客户端上AJAX调用的一个非常好/更好的替代品。看起来有点像这样:

""

如果你真的想在浏览器中渲染它,你可以使用普通的Javascript代替JSX:

var trimmed = $.trim( $('p').text() );

if ( trimmed === '' ){
    //function...
}

另一个选择是使用babel-browser将JSX转换为普通Javascript并使用// 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>'; 。请记住,babel浏览器不再处于活动开发状态,也不适合生产使用。

<?php $username = 'Eric Andre'; ?>
<script type="text/javascript">
  ReactDOM.render(React.createElement(Greeting, { username: "<?php echo $username; ?>" }), document.body);
</script>

答案 1 :(得分:2)

方法1:定义全局变量。

在主PHP文件中:

<script>
    window.reactInit = {
        username: <?php echo $username; ?>
    };
</script>

在您的组件中:

class Greeting extends React.Component {
    constructor(props) {
        super(props);
        this.username = reactInit.username;
    }
}

如果您使用Redux,则可能会发现此方法特别有用。因为您的任何化简器都可以在初始状态建立期间访问此全局变量。

方法2:使用data-*属性。

<div id="app" data-username="<?php echo $username; ?>"></div>

使用data-*传递所有{...app.dataset}属性。

const app = document.getElementById('app');
ReactDOM.render(<Greeting {...app.dataset} />, app);

现在,您可以作为普通道具访问服务器数据。

class Greeting extends React.Component {
    constructor(props) {
        super(props);
        console.log(this.props.username);
    }
}

这种方法不像以前那样灵活,但是似乎与React哲学更加一致。

答案 2 :(得分:1)

您还可以查看https://github.com/erikras/react-redux-universal-hot-example有关如何从客户端调用RESTful API的示例。

具体来说,它使用superagent来进行AJAX调用: https://github.com/visionmedia/superagent