簡體   English   中英

React js 為每個“孩子”添加事件監聽器

[英]React js add event listener for each "children"

嗨,大家好。

我有:

import React,{useState, useEffect} from 'react'

/* Styles */
import css from './MyComponent.module.sass'

const MyComponent= ({children, className, ...props}) => {
    const onOver = (e) => {
        console.log(e.target.offsetLeft);
    }

    //And here i need to add onOver function to each "children" element as onMouseOver event

    return(
        <ul className={`${css.MyComponentWrap} ${className}`}>
            <div className={css.MyComponent}></div>
            {children}
        </ul>
    );
}

export default MyComponent;

我該怎么做?

我在互聯網上搜索了答案,但沒有找到合適的答案。 是否可以在此組件中編寫所有代碼,以便無需向將使用它的組件添加任何內容?

PS抱歉我的英語不好))

更新。

const AnotherComponent = () =>{

    //here is a huge map function

    let mapResult;
    return (
        <MyComponent>
            {mapResult}
        </MyComponent>
    );
}

我有一個巨大而困難的映射,這就是為什么我不能使用@Kox 的答案。

我需要一些類似“MyComponent”中的循環並添加事件或將其作為道具傳遞的東西。

其實我可以,但我認為這不是最好的解決方案

有什么理由不能將偵聽器附加到父級(此處: ul ),並使用target確定哪個元素已被“鼠標懸停”?

 function App() { return ( <MyComponent> <li>Bob</li> <li className="tab">John</li> <li>Sally</li> </MyComponent> ); } function MyComponent({ children }) { function handleClick(e) { const { target: { offsetLeft } } = e; console.log(offsetLeft); } return ( <ul onMouseOver={handleClick}> {children} </ul> ); } // Render it ReactDOM.render( <App />, document.getElementById("react") );
 ul { width: 100px; } li:hover { background-color: #efefef; } .tab { margin-left: 1em; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script> <div id="react"></div>

如果你想將 props 傳遞給你的孩子,請使用 React.PureComponent 和 React.Children API

class MyComponent extends React.PureComponent {
  onOver = event => {
    //do what u want with you event
  }

  render() {
    const childrenHavingOnOverFunction = 
      React.Children.map(this.props.children, child => {
         return React.cloneElement(child, { onOver: this.onOver })
      }
    );

    return (
        <ul className={`${css.MyComponentWrap} ${className}`}>
            <div className={css.MyComponent}></div>
            {childrenHavingOnOverFunction}
        </ul>
    )

  }
};

這似乎是渲染道具的一個很好的用例(通過children道具)。

讓您的組件返回:

return(
  <ul className={`${css.MyComponentWrap} ${className}`}>
   <div className={css.MyComponent}></div>
   {children(onOver)}
  </ul>
);

現在MyComponent應該接受它的孩子作為一個函數來渲染:

<MyComponent>
{(onOver) => {
  // your children components now have access to onOver function
}}
</MyComponent>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM