我有一个像这样的 React 应用程序。
var X = React.createClass({
componentDidMount: function() {
fetch(this.props.feed).then(...);
}
render: function() {
return <div>{this.props.feed}</div>
}
});
feed 属性用于在 componentDidMount 中获取对于特定客户而言唯一的 JSON feed。
将数据从 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-
各种 Prop 的属性,然后使用解构传递所有 Prop {...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);
<罢工>编辑:demo fiddle 罢工>
2018年编辑:updated fiddle
关于reactjs - 有没有正确的方法将数据从 HTML 页面传递到 React 组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36545118/