如何初始化React Materialize在componentDidMount

时间:2019-05-14 08:21:43

标签: reactjs materialize

在用户登录时,我使用条件渲染并添加新标记,直到用户登录,我的Navbar组件才没有Materialize Dropdown标记。但是,我似乎无法使用React.createRef()来引用新标记来初始化Dropdown。 请找到我的项目的链接,您可以在其中创建一个帐户和see the issue for yourself

我认为问题是,我无法在compononentDidMount之后重新创建引用。

我尝试在React.createRef()componentWillReceiveProps中创建ref(componentWillUpdate),但是当我尝试在其中创建ref时却得到了空值。

class Navbar extends Component {
    userRef = React.createRef();

    render() {        
        const { isAuthenticated, user } = this.props.auth;

        // show these when logged
        const authLinks = (
            <ul id="nav-mobile" className="right hide-on-med-and-down">
                <li className="avatar">
                    <a href="#" ref={this.userRef} data-target="dropdown1" className="dropdown-trigger">
                        <div className="avatar">
                        </div>
                        {user.username}
                    </a>
                    <ul id="dropdown1" className="dropdown-content">
                        <li><Link to="/dashboard">Dashboard</Link></li>
                    </ul>
                </li>
            </ul>
        );

        // show these when not logged in
        const guestLinks = (
            <ul id="nav-mobile" className="right hide-on-med-and-down">
                <li><Link to="/login">Login</Link></li>
                <li><Link to="/register">Register</Link></li>
            </ul>
        );
        return (
            <nav>
                {isAuthenticated ? authLinks : guestLinks}
            </nav>
        )
    }
}

当我的导航栏收到新的道具时(当用户成功登录时),我需要引用Dropdown DOM元素,以便在其具有正确的标记时初始化它(window.M.Dropdown.init(this.dropdownRef.current))。

0 个答案:

没有答案
相关问题