[英]Accessing React component children props from the parent
我目前正在為一個用 JavaScript 和 ReactJS 編寫的游戲引擎設計界面。
如果游戲對象具有紋理,則紋理的來源將顯示在游戲對象上。 為此,游戲對象需要具有紋理的引用或更具體地說是紋理的來源。 我希望有一個像下面這樣的 JSX 片段。
<GameObject>
<Texture source="myimage.png" />
</GameObject>
我能想出的獲得參考的最佳解決方案是將紋理作為道具,如下所示:
<GameObject texture={<Texture source="myimage.png" />} />
如果游戲引擎特定的術語有點令人困惑,可以將其視為按鈕組件內的字幕組件,其中字幕組件具有按鈕需要訪問的特定數據。
我的問題歸結為:在沒有黑客或反模式的情況下安裝孩子后是否可以訪問孩子的道具?
由於評論中的鏈接已損壞,因此我附上了一個指向當前react-router
Switch
模塊實現的鏈接,其中解析了子級(請參閱render()
函數)。 同樣在本教程視頻中,作者從父級訪問子級道具。
為了避免再次遇到鏈接過期的相同問題,以下是受react-router
的Switch
啟發時,從父級訪問子級道具的代碼在上述示例中的樣子:
(在游戲對象內)
const { children } = this.props
React.Children.forEach(children, element => {
if (!React.isValidElement(element)) return
const { source } = element.props
//do something with source..
})
你應該可以這樣做this.props.texture.props
。 我不知道它是一種反模式,但我也不認為它是一種常見的模式。 如果您想訪問特定的道具,它肯定看起來可能會破壞封裝。
您不必將元素作為道具傳遞來獲取對它的引用。 您可以通過this.props.children
訪問孩子。
有關更多信息,請參閱 文檔。
這是你在想的那種事情嗎?
const Game = ({ children }) => { // small hack to turn single child, into array if (!children.length) { children = [children]; } children.map((child, i) => { // now have access to props.source in parent console.log(child.props.source); }) return ( < div > { children } < /div> ); } const Texture = ({source}) => { return ( <div>Texture: {source}</div > ); } ReactDOM.render(( < Game > < Texture source = "thing.png" / > < Texture source = "other.png" / > < /Game> ), document.getElementById('game'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id='game'></div>
真的有點亂。
我個人要么給Game
一個紋理數組來加載自己。
或者完全解耦Game
和Texture
,因此數據只以一種方式流動。
什么需要擁有紋理,它的父級應該是什么?
你能定義一個擁有紋理並且是紋理父級的游戲對象嗎? 例如:
<GameObject textureSoure='myimage.png' />
然后 GameObject 渲染紋理(在 GameObject 的 render() 中)?
return <....>
<Texture source={ this.props.textureSource } />
</....>
解決同一問題的另一種方法是:
將必須從孩子有條件地訪問的日期添加到父母道具中......
你永遠不會出錯🙃🙃🙃
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.