onMouseLeave事件无效

时间:2016-10-13 22:01:43

标签: reactjs javascript-events

这是导航组件。此导航组件在运行时呈现。当鼠标用ref“text_nav”进入div时文本应该是可见的,当鼠标用ref“text_nav”离开div时,文本应该隐藏。

onMouseLeave无效

var React = require('React');
var $ = require('jquery');

var Nav = React.createClass({
   getInitialState: function() {
        return {
            items: []
        }
    },
    componentWillMount: function() {
        var _this = this;
        this.serverRequest =
        $.post("/nav", {}, function(result) {
            _this.setState({
                items: result.data
            });
        })
    },

   onMouseEnter: function() {
        this.refs.text_navigator.style = {display: true}
    },
   onMouseLeave: function() {
        this.refs.text_navigator.style = {display: 'none'}
    },
    render: function() {
        var text = this.state.items.map(function(data, index) {
            var icon = "text_" + data.sname;
            return (
                    <div id={icon} key={index} className="text_nav_item">
                            <p>
                                <span><a href={data.url}>{data.title} </a></span>
                            </p>
                     </div>
            );
        });

        return (
                <div id="nav" className="fixed" style={{zIndex: 1018}} onMouseEnter={this.onMouseEnter} onMouseLeave={this.onMouseLeave}>
                    <div id="text_nav" ref="text_navigator" style={{display: 'none'}} >
                        <div id="text_nav_content">
                            {item_text}
                        </div>
                    </div>
                </div>
        )
    }
})

1 个答案:

答案 0 :(得分:1)

首先,您的渲染方法中的参考号为text_nav,而text_navigatoronMouseEnter中的参考号码不是onMouseLeave。但主要问题是您无法按照您尝试的方式设置显示样式,如 this.refs.text_navigator.style = {display: true}

最常用的方法是设置布尔状态,也许称为displayTextNavigator。在getInitialState中,将其设置为false,然后您的onMouseEnteronMouseLeave函数可以是:

  onMouseEnter: function() {
        this.setState({ displayTextNavigator: true})
    },
   onMouseLeave: function() {
        this.setState({ displayTextNavigator: false})
    },

现在,在您的渲染方法中,您可以将包装div更改为:

<div id="text_nav" ref="text_nav" style={{display: this.state.displayTextNavigator ? 'block': 'none'}} > 如果你想让它更具可读性,你可以在渲染方法中将那个三元运算符拉出来。