javascript - ReactJS中已挂载组件的findDOMNode

标签 javascript validation input components reactjs

页面中包含两个 JS 文件,分别为 utility.js 和 utility1.js
utility.js 的代码

var HelloWorld = React.createClass({
  render: function() {
    return (
      <p>
        Hello, <input type="text" ref="mytestinput" placeholder="Your name here" />!<br />
        It is {this.props.date.toTimeString()}
      </p>
    );
  }
});

setInterval(function() {
  React.render(
    <HelloWorld date={new Date()} />,
    document.getElementById('container')
  );
}, 1000);

utility1.js 的代码

var MyComponent = React.createClass({
  handleClick: function() {
    // Explicitly focus the text input using the raw DOM API.
    React.findDOMNode(HelloWorld.refs.mytestinput).focus();
  },
  render: function() {
    // The ref attribute adds a reference to the component to
    // this.refs when the component is mounted.
    return (
      <div>
        <input type="text" ref="myTextInput" />
        <input
          type="button"
          value="Focus the text input"
          onClick={this.handleClick}
        />
      </div>
    );
  }
});

React.render(
  <MyComponent />,
  document.getElementById('container1')
);

这里的问题是我想关注 utility1.js 中 utility.js 的 HelloWorld 组件的输入。我看到他们是一种用于安装组件的 findDOMNode 方法。但这段代码对我不起作用。有人可以试试这个 JS Fiddle here并让我知道可能的解决方案。

最佳答案

您需要创建全局事件系统才能允许这两个组件 communicate with each other如果他们没有亲子关系。以下是有关 global event system 的更多信息

解决方案如下:jsfiddle

var CustomEvents = (function() {
  var _map = {};

  return {
    subscribe: function(name, cb) {
      _map[name] || (_map[name] = []);
      _map[name].push(cb);
    },

    notify: function(name, data) {
      if (!_map[name]) {
        return;
      }

      // if you want canceling or anything else, add it in to this cb loop
      _map[name].forEach(function(cb) {
        cb(data);
      });
    }
  }
})();

关于javascript - ReactJS中已挂载组件的findDOMNode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30497163/

相关文章:

javascript - 在 JavaScript 中单独定位/循环元素,无需 ID 或类

java - 我如何在 Java 中读取 double 值?

C++ 将串行输入读取到字符串

ios - 该应用程序在 Payload/<Appname>.app/<App name> : birthday 中引用了非公共(public)选择器

javascript - JQuery 根据当前选择的文本输入更改 TR 背景颜色

javascript - Google map Places API - 如何使用 Google map 搜索框在多个结果中获取国家/地区、邮政编码、号码、网站 URL

javascript - 为什么 foodModule not defined 错误? Angular js

javascript - 单击加载 PHP 文件

javascript - php和js之间的响应

xcode - 始终将 “Network connection was lost”作为验证问题