我刚刚开始学习ReactJS并试图找出 - 如果 - 我可以将它用于Symfony2应用程序在服务器端生成的现有模板 .
我们的想法是使用ReactJS来更新部分视图(小部件 - 或者从技术点,Symfony2“部分模板”),例如更新评论的计数器,或者将新消息添加到新闻列表的顶部,删除最底部的一个 .
我当然可以只使用对服务器的Ajax调用,从Symfony2 / Twig获取列表的整个模板,并通过jQuery或其他任何东西在DOM中刷新/替换它:
<ul id="list">
<li>1 news</li>
<li>2 news</li>
<li>3 news</li>
<li><strong>4</strong> OLD news - to be removed</li>
</ul>
当新的新闻出现时,它看起来像这样:
<ul id="list">
<li><strong>0</strong> NEW news</li>
<li>1 news</li>
<li>2 news</li>
<li>3 news</li>
</ul>
(即在底部删除“4”并在列表顶部添加“0”) .
这是我想要实现的“小部件”的一个示例,或者更确切地说 - 因为它们已经存在于Twig(PHP模板引擎)模板中 - 为这些模板添加了一些客户端JS动态,这可以被视为小部件一种方式 .
但是如何使用ReactJS呢?
至于我到目前为止的结论,似乎我需要在我的PHP Twig模板中执行类似的操作:
<div id="content">
<ul id="list">
<li>1 news</li>
<li>2 news</li>
<li>3 news</li>
<li>4 news</li>
</ul>
</div>
React.render(
<ul id="list">
<li>1 news</li>
<li>2 news</li>
<li>3 news</li>
<li>4 news</li>
</ul>,
document.getElementById('list')
);
生成相同的列表两次 . 这是因为第一个列表适用于非JS用户类似Google的机器人,第二个列表只是为了通知ReactJS我的列表组件的结构是什么 . 当然,实际上我会动态创建这个列表,如:
<li>{ newsContent }</li>
无论如何,两次创建相同的列表对我来说似乎是一个非常糟糕的主意 . 所以我在想ReactJS是否能够读取我的DOM,并自动弄清楚HTML UL元素是否由LI元素组成,并构建其虚拟DOM?然后我可以为它调用JS React方法?
或许我可以这样做:
-
从服务器获取新的News元素(单个LI)
-
从页面的DOM中获取当前的新闻列表(UL与LI子女)
-
手动删除最底部的一个
-
合并两者,并将其作为包含HTML的新字符串传递给ReactJS?
So to sum it up, is ReactJS able to build Virtual DOM reading my current DOM?
Or, is ReactJS able to render directly from a string (instead JSX), like with the whole UL + all LI elements?
Or even more simple, is it a possibility to convert a string with HTML markup into a ReactJS element (then I could just get the whole new template from the server and pass it to the React's render method)?
UPDATE:
I learnt so far that there's a tool like Babel which compiles JSX into Javascript, which would be of very help in my case. But, how the heck am I going to get a simple .js copy of a Babel? What I see that there are are only kind of npm (Node.JS?) packages. Is there possible to just include it like a normal JS file lib?
1 回答
你想要的是PHP渲染有效的“React”标记(包括校验和和特殊ID),所以当React看到它时,它可以挂载在它上面并继续执行 .
这似乎有所帮助:https://packagist.org/packages/camspiers/reactjs-php-render