简体   繁体   English

如何从event.target获取react元素

[英]How to get react element from event.target

I have attached an event listener to the parent element to listen for a non-synthetic-event and I wonder if there is a nice way to get reference to the component which triggers the event to use it's properties 我已将事件侦听器附加到父元素以侦听非合成事件,并且我想知道是否有一种很好的方法来获取对触发该事件以使用其属性的组件的引用

I need to postpone the rendering of item.component until the nonSyntheticEvent occurs 我需要推迟item.component的呈现,直到nonSyntheticEvent发生

const items = [
  {
    name: "click me",
    component: function First() {
      return <strong>asd</strong>;
    }
  },
  {
    name: "click me 2",
    component: function Second() {
      return <b>oasd</b>;
    }
  }
];

class Component extends React.Component {
  componentDidMount() {
    this.el.addEventListener("nonSyntheticEvent", event =>
      this.nonSyntheticEventHandler(event)
    );
  }

  nonSyntheticEventHandler(event) {

    // how to get reference to item
    // from event.target to render it's item.component

    const el = React.createElement(item.component);
    ReactDOM.render(el, event.target);
  }

  render() {
    return (
      <div ref={ref => { this.el = ref; }}>
        {this.props.items.map(item => <Child {...item} />)}
      </div>
    );
  }
}

<Component items={items} />

With React 16.3 React.createRef() is introduced which can be used in Component to create reference before the Child component is rendered. 在React 16.3中引入了React.createRef() ,可在Component使用该Component在呈现Child组件之前创建引用。

for example in Component.constructor a reference to each child can be created in the state 例如在Component.constructor ,可以在状态中创建对每个子项的引用

this.state = {
  items: items.map(item => ({
    ...item,
    reference: React.createRef()
  }))
};

and then in the Child component can be used from props: 然后可以在子组件中使用道具:

function Child(props){
  return (
    <div ref={props.reference}>
      <span>{props.name}</span>
    </div>
  );
}

and then in the nonSyntheticEventHandler the item can be obtained like so: 然后在nonSyntheticEventHandler中可以按以下方式获得项目:

const found = this.state.items.find(item => {
  return item.reference.current === event.target;
});

working example in Codesandbox.io Codesandbox.io中的工作示例

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

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