ReactJS onClick setState到不同的元素

时间:2016-06-26 12:27:13

标签: javascript reactjs

我是新手做出反应,我有一点问题。也许有人可以帮助我。

所以问题是我无法使用onCLick函数来调整我想要的元素。现在我想在

时删除导航
import React from "react";
import ReactDOM from "react-dom";

export default class Nav extends React.Component {
    constructor() {
        super();
        this.state = {navStatus: "navHide"};
    }

    navClose() {
        var navOpened = document.getElementById("myNav");
        navOpened.setState({navStatus: "navHide"});
    }

    navOpen() {
        this.setState({navStatus: "navShow"});
    }

    render() {
        return(
            <nav onClick={this.navOpen.bind(this)}>
                <div id="myNav" className={this.state.navStatus}>
                    <div className="navClose" onClick={this.navClose.bind(this)}>
                        <object className="navCloseBtn" type="image/svg+xml" data="svg/close.svg"></object>
                    </div>                  
                </div>
            </nav>
        );
    }
}

我遇到的错误是

nav.js:12 Uncaught TypeError: navOpened.setState is not a function

另外,如果您注意到我可以在代码中改进的某些模式,我会非常感谢您的反馈。

谢谢!

3 个答案:

答案 0 :(得分:5)

只有反应组件具有setState方法。 工作示例:

import React from "react";
import ReactDOM from "react-dom";

export default class Nav extends React.Component {
constructor() {
    super();

    this.state = {
        navStatus: "navHide"
    };

    this.navClose = this.navClose.bind(this);
    this.navOpen = this.navOpen.bind(this);
}

navClose(e) {
    e.stopPropagation();
    this.setState({
        navStatus: "navHide"
    });
}

navOpen() {
    this.setState({
        navStatus: "navShow"
    });
}

render() {
    return(
        <nav onClick={this.navOpen}>
            <div id="myNav" className={this.state.navStatus}>
                <div className="navClose" onClick={this.navClose}>
                    <object className="navCloseBtn" type="image/svg+xml" data="svg/close.svg"></object>
                </div>                  
            </div>
        </nav>
    );
}

此外,您应该在构造函数中绑定事件处理程序,而不是render方法。

答案 1 :(得分:1)

import React from "react";
import ReactDOM from "react-dom";

export default class Nav extends React.Component {
constructor() {
    super();
    this.state = {navStatus: "navHide"};
}

navClose() {
    var navOpened = document.getElementById("myNav");
    this.setState({navStatus: "navHide"});
}

navOpen() {
    this.setState({navStatus: "navShow"});
}

render() {
    return(
        <nav onClick={this.navOpen.bind(this)}>
            <div id="myNav" className={this.state.navStatus}>
                <div className="navClose" onClick={this.navClose.bind(this)}>
                    <object className="navCloseBtn" type="image/svg+xml" data="svg/close.svg"></object>
                </div>                  
            </div>
        </nav>
    );
}
}

答案 2 :(得分:0)

您还可以使用内联函数

segmentation fault 11

但是有些人认为它存在性能问题https://medium.com/front-end-weekly/dont-use-inline-arrow-functions-as-properties-e3cae2680b9d