我有一个像这样的React应用程序。
var X = React.createClass({ componentDidMount: function() { fetch(this.props.feed).then(...); } render: function() { return <div>{this.props.feed}</div> } });
feed道具用于在componentDidMount中获取JSON订阅源,该JSON订阅对特定客户而言是唯一的。
将数据从HTML传递到我的React应用程序以对其进行参数化将很方便:
<html> <body> <div id="app" feed='custom_feed.json'></div> </body> </html
我当前的解决方案如下所示:
var root = document.getElementById('app'); var feed = root.getAttribute('feed') ReactDOM.render(<X feed={feed}/>, root);
这显然是可行的,但感觉应该有一个更惯用的解决方案。还有更多的React方法可以做到这一点吗?
我已经data-为各种道具使用了属性,然后使用destructuring传递了所有道具{...dataset},例如:
data-
{...dataset}
HTML:
<div id="app" data-feed='custom_feed.json' data-someprop='value'></div>
JS:
var root = document.getElementById('app'); ReactDOM.render(<X {...(root.dataset)} />, root);
编辑: 演示小提琴 编辑2018:更新小提琴