首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >React JS,使用onClick中的参数来更改状态?

React JS,使用onClick中的参数来更改状态?
EN

Stack Overflow用户
提问于 2020-06-15 11:09:20
回答 2查看 30关注 0票数 0

我需要有参数对我的点击发送一个字符串,这取决于什么按钮有人点击。我意识到要设置参数,我需要在render () {}中创建一个函数,但是现在当我尝试使用this.setState({zone: location})时,我得到了以下错误:

代码语言:javascript
复制
TypeError: Cannot read property 'setState' of undefined

下面是我的代码:

代码语言:javascript
复制
import React, { Component } from "react";
import "./styles/homeStyle.css";
import timerIcon from "./styles/media/timer_clock.png";
import streaksIcon from "./styles/media/streaks_fire.png";
import guideIcon from "./styles/media/guide_meditation.png";

class Main extends Component {
    state = {
        zone: "home",
    };
    render() {
        return (
            <React.Fragment>
                <div id="diagonal_shape"></div>
                <div className="row">
                    <div className="col s12" id="title">
                        <h4 className="center-align">
                            Peaceful<span id="title_steps"> Steps</span>
                            <br />
                            {this.state.zone}
                        </h4>
                    </div>
                    <div id="nav_bar">
                        <div className="col s4" id="goto_timer">
                            <p className="center-align">
                                <img src={timerIcon} width="60%" alt="clock" onClick={() => goTo("timer")} />
                                <br />
                                Timer
                            </p>
                        </div>
                        <div className="col s4">
                            <p className="center-align">
                                <img src={streaksIcon} width="60%" alt="fire" onClick={() => goTo("stats")} />
                                <br />
                                Stats
                            </p>
                        </div>
                        <div className="col s4">
                            <p className="center-align">
                                <img src={guideIcon} width="60%" alt="meditating" onClick={() => goTo("guides")} />
                                <br />
                                Guides
                            </p>
                        </div>
                    </div>
                </div>
            </React.Fragment>
        );
        function goTo(location) {
            console.log("yes " + location);
            this.setState({ zone: location });
        }
    }
}

export default Main;

我很确定这是因为我不能在render函数中使用this.setState({}),但我不知道该如何让它工作。

EN

回答 2

Stack Overflow用户

发布于 2020-06-15 11:12:56

出现错误的原因是因为您在返回后定义了一个function inside render方法。

注意这里的单词function (而不是箭头fun)。当您定义一个函数时,js引擎会将其提升到其作用域的顶部,其值为undefined。这就是你得到这个错误的原因。

从技术上讲,您可以在render方法中定义处理程序,但必须确保使用箭头函数并在render方法return语句之前定义它。See demo here

但是,作为最佳实践,不要在方法中定义处理程序。

在render中编写处理程序的代码片段

代码语言:javascript
复制
export class App extends Component {
  state = {
    name: "hello"
  };

  render() {
    console.log("state", this.state.name);
    const clickMe = () => {
      console.log(this.setState({ name: "hi!!!!" }));
    };
    return (
      <div className="App">
        <h1>Hello CodeSandbox</h1>
        <h2>Start editing to see some magic happen!</h2>
        <button onClick={() => clickMe()}>Click Me</button>
      </div>
    );
  }
}
export default App;
票数 0
EN

Stack Overflow用户

发布于 2020-06-15 11:13:24

如果在函数中执行state更新,则不能在类方法中定义函数。将goTo方法定义为class方法,然后像单击按钮时调用this.goto("some string")一样调用它。

您需要将this bindgoTo方法,或者只使用arrow function

代码语言:javascript
复制
class Main extends Component {

    constructor(props) {
        super(props)
        this.state = {
            zone: "home",
        };
        this.goTo = this.goTo.bind(this);
    }

    goTo(location) {
        console.log("yes " + location);
        this.setState({ zone: location });
    }

    render() {
        return (
            <React.Fragment>
                <div id="diagonal_shape"></div>
                <div className="row">
                    <div className="col s12" id="title">
                        <h4 className="center-align">
                            Peaceful<span id="title_steps"> Steps</span>
                            <br />
                            {this.state.zone}
                        </h4>
                    </div>
                    <div id="nav_bar">
                        <div className="col s4" id="goto_timer">
                            <p className="center-align">
                                <img src={timerIcon} width="60%" alt="clock" onClick={() => this.goTo("timer")} />
                                <br />
                                Timer
                            </p>
                        </div>
                        <div className="col s4">
                            <p className="center-align">
                                <img src={streaksIcon} width="60%" alt="fire" onClick={() => this.goTo("stats")} />
                                <br />
                                Stats
                            </p>
                        </div>
                        <div className="col s4">
                            <p className="center-align">
                                <img src={guideIcon} width="60%" alt="meditating" onClick={() => this.goTo("guides")} />
                                <br />
                                Guides
                            </p>
                        </div>
                    </div>
                </div>
            </React.Fragment>
        );
    }
}
export default Main;

如果您想在class方法中使用function,并且想要访问类fields/methods,则将class this变量绑定到该函数,或者只使用arrow function。这样,function中的this变量将引用class

代码语言:javascript
复制
class Main extends Component {
    state = {
        zone: "home",
    };


    render() {

        function goTo(location) {
            console.log("yes " + location);
            this.setState({ zone: location });
        }
        goTo = goTo.bind(this);

        return (
            <React.Fragment>
                <div id="diagonal_shape"></div>
                <div className="row">
                    <div className="col s12" id="title">
                        <h4 className="center-align">
                            Peaceful<span id="title_steps"> Steps</span>
                            <br />
                            {this.state.zone}
                        </h4>
                    </div>
                    <div id="nav_bar">
                        <div className="col s4" id="goto_timer">
                            <p className="center-align">
                                <img src={timerIcon} width="60%" alt="clock" onClick={() => this.goTo("timer")} />
                                <br />
                                Timer
                            </p>
                        </div>
                        <div className="col s4">
                            <p className="center-align">
                                <img src={streaksIcon} width="60%" alt="fire" onClick={() => this.goTo("stats")} />
                                <br />
                                Stats
                            </p>
                        </div>
                        <div className="col s4">
                            <p className="center-align">
                                <img src={guideIcon} width="60%" alt="meditating" onClick={() => this.goTo("guides")} />
                                <br />
                                Guides
                            </p>
                        </div>
                    </div>
                </div>
            </React.Fragment>
        );


    }
}
export default Main;

,我建议使用第一种方法,因为它更具可读性,更简洁。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62380744

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档