[英]React - Set property of a component from another Component
我是完全菜鸟,所以请耐心等待。
我正在创建一个网页,上面有灰尘。 我没有使用react创建整个页面,这不是一个选择。
我想要做的是加载一个json文件并使用该数据设置页面上组件的属性。 页面呈现后,这些属性将不会更改。
我设法加载json并设置组件的属性。 我还需要在不是第一个组件的子组件的其他组件中重用该组件的某些属性。
我想基本上我需要创建一组全局数据,供页面上的任何组件使用。 我来自一个有角度的背景,所以也许这会使我偏离路线
这是我到目前为止的
var ReleaseList=React.createClass({
getInitialState: function(){
return {
allReleases:[]
}
},
showResults :function(ReleaseData){
this.setState({
allReleases :ReleaseData
});
},
getReleases:function(){
fetch('http://imac.local:5757/s0dj8a.json').then(function(response) {
// Convert to JSON
return response.json();
}).then(function(j) {
var ReleaseData=j.releaseDetail[0]
this.showResults(ReleaseData)
}.bind(this));
},
componentDidMount(){
this.getReleases();
},
render:function(){
return (
<h1>{this.state.allReleases.title}</h1>
)
}
});
var ReleaseDataTitle=React.createClass({
render:function(){
return (
<div>
<h2>{this.props.title}</h2>
// This needs to be the same as this.state.allReleases.title in the previous component
</div>
)
}
});
ReactDOM.render(<ReleaseList/>, document.getElementById('content'));
ReactDOM.render(<ReleaseDataTitle title={'I need this to be the same as this.state.allReleases.title in <ReleaseList />'}/>, document.getElementById('banner'));
我不会考虑使用React来呈现您网站的静态小部分,就像我不太了解JS一样,我不会使用jQuery一样-对于如此简单的任务,这是不必要的下载。 但是,我将考虑Preact ,它是为以下情况而制作的3kb React克隆:站点/应用程序的一小部分具有相似的API。
但是这是我将如何使用React的方法(我想Preact非常相似)。
页面呈现后,这些属性将不会更改。
如果数据没有改变,您甚至不需要将数据存储到全局变量,只需渲染React组件,同时将获取的数据作为props
传递即可。
fetch('http://imac.local:5757/s0dj8a.json').then(function(response) {
return response.json()
}).then(function(data) {
ReactDOM.render(<First data={data} />, document.getElementById('first'))
ReactDOM.render(<Second data={data} />, document.getElementById('second'))
// And any other React component you wish to add to DOM
})
现在,这些元素中的每个数据都可以使用this.props.data
。 现在,您可以使用此数据做任何您想做的事情:格式化,更改,传递给子代,渲染等 。
PS! 我甚至是React的创建者都建议使用ES6类,尤其是如果您刚刚开始..
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.