有没有正确的方法将数据从 HTML 页面传递到 React 组件? [英] Is there a right way to pass data into a React component from the HTML page?
问题描述
我有一个这样的 React 应用.
var X = React.createClass({componentDidMount:函数(){获取(this.props.feed).then(...);}渲染:函数(){返回 {this.props.feed}}});
提要道具用于在 componentDidMount 中获取特定客户独有的 JSON 提要.
将数据从 HTML 传递到我的 React 应用程序以对其进行参数化会很方便:
<身体><div id="app" feed='custom_feed.json'></div></html
我目前的解决方案如下:
var root = document.getElementById('app');var feed = root.getAttribute('feed')ReactDOM.render(, root);
这显然有效,但感觉应该有一个更惯用的解决方案.有没有更多的 React 方法来做到这一点?
我已经为各种 props 使用了 data-
属性,然后使用解构传递了所有的 props {...dataset}
,例如:
HTML:
<div id="app" data-feed='custom_feed.json' data-someprop='value'></div>
JS:
var root = document.getElementById('app');ReactDOM.render( , root);
I have a React app like this.
var X = React.createClass({
componentDidMount: function() {
fetch(this.props.feed).then(...);
}
render: function() {
return <div>{this.props.feed}</div>
}
});
The feed prop is used to get a JSON feed in componentDidMount that's unique for a particular customer.
It would be convenient to pass data into my React app from the HTML to parameterise it:
<html>
<body>
<div id="app" feed='custom_feed.json'></div>
</body>
</html
My current solution looks like this:
var root = document.getElementById('app');
var feed = root.getAttribute('feed')
ReactDOM.render(<X feed={feed}/>, root);
This obviously works, but it feels like there ought to be a more idiomatic solution. Is there a more React way to do this?
I have used data-
attributes for various props, then passed all the props using destructuring {...dataset}
, for example:
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);
Edit: demo fiddle
Edit 2018: updated fiddle
这篇关于有没有正确的方法将数据从 HTML 页面传递到 React 组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!