[英]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.