从父级访问React组件子级道具 [英] Accessing React component children props from the parent

查看:69
本文介绍了从父级访问React组件子级道具的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在设计用JavaScript和ReactJS编写的游戏引擎的界面。

I am currently in the process of designing the interface for a game engine that is written in JavaScript and ReactJS.

如果游戏对象有纹理,则源纹理将显示在游戏对象上。为了实现这一点,游戏对象需要具有纹理的引用,或者更具体地说是纹理的来源。我希望有一个类似下面的JSX片段。

If a game object has a texture, the source of the texture will show up on the game object. For that to work, a game object needs to have the reference of the texture or more specifically the source of a texture. What I'm hoping for is to have a JSX snippet like the following one.

<GameObject>
  <Texture source="myimage.png" />
</GameObject>

我能想出的最佳解决方案是将纹理作为道具,像这样:

The best solution I could come up with to get the reference is to have the texture as a prop, like so:

<GameObject texture={<Texture source="myimage.png" />} />

如果特定于游戏引擎的术语有点令人费解,可以将其视为内部的标题组件一个按钮组件,其中标题组件具有按钮需要访问的特定数据。

If the game engine-specific terminology is a bit too bewildering, think of it as a caption component inside a button component, where the caption component has specific data the button needs to access.

我的问题归结为:孩子们有可能访问孩子的道具没有黑客或反模式安装?

My question boils down to this: Is it possible to access children's prop after the children have been mounted without hacks or being an anti-pattern?

推荐答案

因为评论中的链接被破坏了,我附上一个链接到当前 react-router 切换解析子节点的模块实现(参见 render()功能)。另请参阅本教程视频作者从父母那里访问儿童道具。

Because the links in the comments are broken, I enclose a link to the current react-router Switch module implementation where children are parsed (see the render() function). Also in this tutorial video the author accesses children props from parent.

为了不再遇到链接到期的相同问题,以下是从父级访问子道具的代码看起来是这样的上面的例子受到 react-router 的启发开启

To not bump into the same problem with link expiring again, here is how the code for accessing children props from parent would look like for above example when inspired by react-router's Switch:

(在GameObject内)

(inside GameObject)

const { children } = this.props

React.Children.forEach(children, element => {
  if (!React.isValidElement(element)) return

  const { source } = element.props

  //do something with source..
})

这篇关于从父级访问React组件子级道具的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆