简体   繁体   中英

why tooltip is not hide on mouseleave event in react?

I am trying to show tooltip on mouse enter and hide on mouse leave .first i make a simple demo which is working fine. https://codesandbox.io/s/exciting-shannon-4zuij?file=/src/list.js

above code working fine on hover it show's the tooltip and hide on leave.

see same concept i apply on a application.(this code is not working) https://codesandbox.io/s/cool-liskov-8rvjw?file=/src/App.js

when I hover a item is show the tooltip.but it is not hiding the tooltip when you leaving the item.something went wrong.

const Student = ({students,clickHandler}) => {
    console.log(students,"---ee")
    const [selectedStudent,setSelectedStudent]  = useState(null)

    const onMouseHandler = (student,e)=>{
        student.visibility = true
        setSelectedStudent(student)
    }

    const onMouseLeaveHandler = (student)=>{
        console.log('======',student)
        student.visibility = false
        setSelectedStudent(student)
    }
    return (
        <ul className="student-container">
            {
                students && students.length > 0 ? students.map((student,index)=>{
                    return (
                        <li key={index} onClick={()=>{
                            clickHandler(student)
                        }}
                            onMouseLeave={()=>{
                                onMouseLeaveHandler(student)
                            }}
                            onMouseEnter={(e)=>{
                            onMouseHandler(student,e)
                        }} style={{position:'relative'}}>
                        <a><span>{student.name}</span></a>
                            {student.visibility? <ToolTip showToolTip={student.visibility} selectedStudent={selectedStudent}/>:null}
                        </li>
                    )
                }):null
            }
        </ul>
    );
};

export default Student;

Step too reproduce

  1. Hover on first item Raj
  2. and then try to hover sameer .both tooltip will display.I want only one tooltip will be display which is hovered.

I want my handlers should be in my functional component . I don't want to move these handler to parent component and pass handler as a props

In your demo it's also not work well, - one hide only when open another. when you set student.visibility you not set state, so nothing has rerendered.

Then when you call setSelectedStudent you pass there just the same referance as was before, since it's the same object, so the state not changed, and again - nothing got rerendered.

What you have to do is pass the updated student in a new variable. like so:

setSelectedStudent({...student})

Then all should work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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