我知道这不是一种功能性方法,无法在React组件中执行类似this.parent的操作,而且我似乎无法在React组件实例中找到任何指向父级的属性,但我只是希望能够在需要的地方执行一些自定义操作.

在任何人浪费时间解释这不是功能性react "方式"之前,请理解我需要它,因为我正试图实现以下目标:

Build a transpiler for Meteor's Spacebars templating engine, whose rendering model does take into consideration parent components/templates.

我已经构建了一个transpiler,可以修改输出jsx来实现这一点.我通过在所有子组件中传递parent={this}来实现这一点.然而,在这件事发生后,我突然想到,也许我只是不知道有什么东西可以让我访问父组件实例without additional transpilation modifications.

任何提示都将不胜感激.

推荐答案

Update for React 0.13 and newer

Component._owner在React 0.13中被弃用,而_currentElementthis._reactInternalInstance中不再作为密钥存在.因此,使用下面的解决方案.

另一种 Select 是,从2016年开始.


你已经认识到,这几乎不是一件好事,但我在这里重复这一点,供那些不太了解这个问题的人使用:this is generally an improper way to get things done in React.

public API中没有任何东西可以让你得到你想要的.您可能可以使用React内部代码来实现这一点,但因为它是一个私有API,所以在any time.时很容易崩溃

我重复一遍:几乎可以肯定的是,您不应该在任何类型的生产代码中使用它.

也就是说,可以使用this. _reactInternalInstance获取当前组件的内部实例.在这里,您可以通过_currentElement属性访问元素,然后通过_owner._instance访问owner实例.

下面是一个例子:

var Parent = React.createClass({
  render() {
      return <Child v="test" />;
  },

  doAThing() {
    console.log("I'm the parent, doing a thing.", this.props.testing);
  }
});

var Child = React.createClass({
  render() {
    return <button onClick={this.onClick}>{this.props.v}</button>
  },

  onClick() {
    var parent = this._reactInternalInstance._currentElement._owner._instance;
    console.log("parent:", parent);
    parent.doAThing();
  }
});

ReactDOM.render(<Parent testing={true} />, container);

这里是a working JSFiddle example:http://jsfiddle.net/BinaryMuse/j8uaq85e/

Reactjs相关问答推荐

使用React Router多姆表单组件附加/?地址栏中基本URL的索引

如何使用mui为可重复使用的react 按钮应用不同的风格

props 可以在Reaction中锻造吗?

Next.js-图像组件加载问题

Reactjs中的chartjs和reaction-chartjs-2的问题

我想删除NextJs中的X轴标签APEXCHARTS

为什么登录错误和密码在创建Reaction-Hook-Form后立即被删除?

Next.js Next-Auth登录函数重定向到http://localhost:3000/api/auth/error

子路径上未定义useMatches句柄

在ReactJS的monaco编辑器中添加美人鱼语法

React - 函数组件 - 点击两次问题处理

当我在 React Router Dom 中使用两个参数并直接在页面上导航时,数据获取没有发生

React - 使用 useEffect 还是直接在 onChange 方法中更改值对性能最好?

@react-three/postprocessing 没有匹配的从 three.module.js 导出以导入WebGLMultisampleRenderTarget

如何从 React Redux store 中删除特定项目?

react 本机日历

如何制作基于对象 struct 呈现数据的可重用组件?

如何定制 React 热 toastr ?

如何在组件文件夹内的react 组件文件中导入外部css文件?

React 似乎在触发另一个组件时重新渲染了错误的组件