简体   繁体   English

通过DOM元素作为React中的道具

[英]Pass DOM Element as a prop in React

So I have a component that needs a DOM element passed in as a prop. 因此,我有一个需要将DOM元素作为道具传入的组件。 I'm trying to use it in another component like so: 我正在尝试在另一个组件中使用它,如下所示:

    <div>
        <div className="myPropDiv" ref="myPropDiv">...</div>
        <CustomComponent view={ this.refs.myPropDiv } />
    </div>

But that doesn't work because (I suspect) the DOM hasn't been rendered at the point I'm calling this.refs.myPropDiv . 但这不起作用,因为(我怀疑)在我称之为this.refs.myPropDiv尚未渲染DOM。 How would I accomplish something like this? 我将如何完成这样的事情?

In most situations this is not a good idea, and at least it doesn't look like it is following the React way. 在大多数情况下,这不是一个好主意,至少看起来不像在遵循React方法。

Firstly by getting that div via refs, you don't get DOM element but rather backing instance of that div. 首先,通过引用获取该div,您不会获得DOM元素,而是支持该div的实例。 You can get the DOM element like toomanyredirects is suggesting. 您可以像toomanyredirects所建议的那样获得DOM元素。

What are you trying to achieve anyway? 您到底想达到什么目的? One advantage of React is you don't have to mess with original DOM, but play with the virtual one. React的优点之一是您不必弄乱原始的DOM,而可以使用虚拟的DOM。 If you want to just display that div inside your component, than pass it like this. 如果您只想在组件内部显示该div,则可以像这样传递它。

<CustomComponent> <div className="myPropDiv" ref="myPropDiv">...</div> </CustomComponent>

Then, you can access that div inside your CustomComponent as props.children. 然后,您可以作为props.children在CustomComponent中访问该div。

You can't directly access the DOM, but you can access the DOM element for a React component with ReactDOM.findDOMNode(component) , so to use it inside a componentDidMount call you'd use: 您不能直接访问DOM,但是可以使用ReactDOM.findDOMNode(component)访问React组件的DOM元素,因此可以在您要使用的componentDidMount调用中使用它:

var MyComponent = React.createComponent({
  ...
  componentDidMount: function() {
    var component = this,
      node = ReactDOM.findDOMNode(component);
  }
  ...
});

Then if you are looking for a child node of that parent DOM node, you can traverse the DOM normally from that node, for example: 然后,如果您正在寻找该父DOM节点的子节点,则可以从该节点正常遍历DOM,例如:

var childNode = node.querySelectorAll('.child-node-class')[0];

Then you can pass it to wherever you originally wanted it. 然后,您可以将其传递到您最初想要的任何地方。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM