我目前正在设计用JavaScript和ReactJS编写的游戏引擎界面。
如果游戏对象具有纹理,则纹理的来源将显示在游戏对象上。为了实现这一点,游戏对象需要具有纹理的引用,或者更具体地说是纹理的来源。我希望有一个像下面这样的JSX片段。
<GameObject>
<Texture source="myimage.png" />
</GameObject>
我能想出的最佳解决方案是将纹理作为道具,如下所示:
<GameObject texture={<Texture source="myimage.png" />} />
如果特定于游戏引擎的术语有点令人费解,可以将其视为按钮组件中的标题组件,其中标题组件具有按钮需要访问的特定数据。
我的问题可以归结为:孩子们在没有黑客或者反模式的情况下安装后,是否有可能进入儿童的道具?
答案 0 :(得分:9)
由于评论中的链接已损坏,我将link括在当前<mui:ModernWindow x:Class="SailPost.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mui="http://firstfloorsoftware.com/ModernUI"
Title="mui" IsTitleVisible="True"
LogoData="F1 M 24.9015,43.0378L 25.0963,43.4298C 26.1685,49.5853 31.5377,54.2651 38,54.2651C 44.4623,54.2651 49.8315,49.5854 50.9037,43.4299L 51.0985,43.0379C 51.0985,40.7643 52.6921,39.2955 54.9656,39.2955C 56.9428,39.2955 58.1863,41.1792 58.5833,43.0379C 57.6384,52.7654 47.9756,61.75 38,61.75C 28.0244,61.75 18.3616,52.7654 17.4167,43.0378C 17.8137,41.1792 19.0572,39.2954 21.0344,39.2954C 23.3079,39.2954 24.9015,40.7643 24.9015,43.0378 Z M 26.7727,20.5833C 29.8731,20.5833 32.3864,23.0966 32.3864,26.197C 32.3864,29.2973 29.8731,31.8106 26.7727,31.8106C 23.6724,31.8106 21.1591,29.2973 21.1591,26.197C 21.1591,23.0966 23.6724,20.5833 26.7727,20.5833 Z M 49.2273,20.5833C 52.3276,20.5833 54.8409,23.0966 54.8409,26.197C 54.8409,29.2973 52.3276,31.8106 49.2273,31.8106C 46.127,31.8106 43.6136,29.2973 43.6136,26.197C 43.6136,23.0966 46.127,20.5833 49.2273,20.5833 Z"
ContentSource="/Pages/SailPostMonitor.xaml">
react-router
模块实现中,其中解析子项(请参阅Switch
函数)。同样在this tutorial video中,作者从父母那里访问儿童道具。
为了不再遇到与链接到期相同的问题,以下是在render()
的{{1}} react-router
的启发下,从父级访问子道具的代码看起来像上面的例子:
(在GameObject内)
Switch
答案 1 :(得分:2)
您应该能够this.props.texture.props
。我并不认为它是一种反模式,但我认为这也不是一种常见的模式。如果你想访问一个特定的道具,它看起来肯定会破坏封装。
您不必将元素作为prop传递以获取对它的引用。您可以通过this.props.children
访问儿童。
有关详细信息,请参阅documentation。
答案 2 :(得分:1)
这是你想的那种吗?
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'));
&#13;
<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>
&#13;
真的有点乱。
我个人会给Game
一个纹理数组加载自己。
或完全解耦Game
和Texture
,因此数据只会以一种方式流动。
答案 3 :(得分:0)
什么需要拥有纹理,它的父母应该是什么?
你能定义一个拥有并且是纹理的父对象的GameObject吗?例如:
<GameObject textureSoure='myimage.png' />
然后GameObject渲染纹理(在GameObject&#39;渲染())?
return <....>
<Texture source={ this.props.textureSource } />
</....>