简体   繁体   English

使用 JSX 的 React Button 的 onClick 方法

[英]onClick method of React Button using JSX

I started learning the basics of JS and wrote a small example to examine how buttons work in React using JSX, but I find it to be a bit confusing.我开始学习 JS 的基础知识,并写了一个小例子来检查按钮如何使用 JSX 在 React 中工作,但我发现它有点令人困惑。

I first create a React component and initialize a variable called bar with value 'bar' in the constructor.我首先创建一个 React 组件并在构造函数中初始化一个名为bar的变量,其值为'bar'

I'd like to have this value change to 'baz' when a button is pressed.我希望在按下按钮时将此值更改为'baz'

My code looks like this:我的代码如下所示:

<div id="root"></div>
<script type="text/babel">

    class Foo extends React.Component {
      constructor(props) {
        super(props);
        this.bar = 'bar'
      }

      baz(){
        this.bar = 'baz'
      }

      render() {
        return (
          <div>
            <button onClick={this.baz()}>baz</button>
            <p>{this.bar}</p>
          </div>
        );
      }
    }

    ReactDOM.render(
      <Foo />,
      document.getElementById('root')
    );

</script>

Contrary to my expectations, the value 'baz' is shown right away when I load the page containing this code in my browser.与我的预期相反,当我在浏览器中加载包含此代码的页面时,会立即显示值'baz'

I'm sorry for asking a probably very newbie question, but I don't understand why 'baz' is shown right away, instead of only after I pressed the button.我很抱歉问了一个可能非常新手的问题,但我不明白为什么会立即显示'baz' ,而不是在我按下按钮后才显示。 Thank you for your time.感谢您的时间。 :) :)

You can try this:你可以试试这个:

class Foo extends React.Component {
  constructor(props) {
    super(props);
    this.state = { text: "bar" };
  }

  baz() {
    this.setState({ text: "baz" });
  }

  render() {
    return (
      <div>
        <button onClick={() => this.baz()}>baz</button>
        <p>{this.state.text}</p>
      </div>
    );
  }
}

ReactDOM.render(<Foo />, document.getElementById("root"));

The thing is to update the screen (DOM) its better to change state to let the component re-render.事情是更新屏幕(DOM)最好改变状态让组件重新渲染。 And for the problem that value was initially changed , other answers explain them well而对于 value 最初被改变的问题,其他答案很好地解释了它们

The way you are trying to use function is incorrect.您尝试使用函数的方式不正确。 Refer to one of the below two methods.请参考以下两种方法之一。 Also, bind your function to this context in the constructor.此外,在构造函数中将您的函数绑定到此上下文。

this.baz = this.baz.bind(this);

Then然后

onClick={this.baz}

OR或者

onClick={() => this.baz()}

I pointed out the solution in a comment above, so, I'll thresh out that comment a bit more...我在上面的评论中指出了解决方案,所以,我会更多地对该评论进行脱粒......

You have...你有...

<button onClick={this.baz()}>baz</button>

You want...你要...

<button onClick={() => this.baz()}>baz</button>

I have also threshed out the rest of your code to produce the result you wanted ("I'd like to have this value change to 'baz' when a button is pressed.").我还对其余代码进行了筛选,以产生您想要的结果(“我希望在按下按钮时将此值更改为 'baz'。”)。 You also needed...你还需要...

this.setState(this);

See a full working example here:在此处查看完整的工作示例:

https://codesandbox.io/s/vj904qy4o0 https://codesandbox.io/s/vj904qy4o0

The reason baz is shown right away is because you're calling the function in the click binding.立即显示baz的原因是因为您正在调用单击绑定中的函数。 You should also bind your click handler to your React class.您还应该将您的点击处理程序绑定到您的 React 类。 Here's an example of how this should look:这是一个示例,说明它的外观:

<div id="root"></div>
<script type="text/babel">

    class Foo extends React.Component {
      constructor(props) {
        super(props);
        this.bar = 'bar';
        this.handleClick = this.handleClick.bind(this);
      }

      handleClick() {
        this.bar = 'baz';
      }

      render() {
        return (
          <div>
            <button onClick={this.handleClick}>baz</button>
            <p>{this.bar}</p>
          </div>
        );
      }
    }

    ReactDOM.render(
      <Foo />,
      document.getElementById('root')
    );

</script>

You're calling the baz function during the render, that's why the change happens immediately:您在渲染期间调用baz函数,这就是更改立即发生的原因:

<button onClick={this.baz()}>baz</button>

If you pass a function instead of calling a function, the function will get called when the button is pressed instead:如果您传递一个函数而不是调用一个函数,则该函数将在按下按钮时被调用:

<button onClick={() => this.baz()}>baz</button>

You need to store your values in state, and then bind you click handler to the component.您需要将值存储在状态中,然后将单击处理程序绑定到组件。 Then use setState() to change the value of state.然后使用setState()改变 state 的值。 When state changes, your component will re-render:当状态改变时,你的组件将重新渲染:

class Foo extends React.Component {
      constructor () {
        super()
        this.state = {
          bar: 'bar'
        }
        this.handleClick = this.handleClick.bind(this)
      }
      handleClick () {
        this.setState({
          bar: 'baz'
        })
      }
      render () {
        return (
          <div>
            <button onClick={this.handleClick}>baz</button>
            <p>{this.state.bar}</p>
          </div>
        )
      }
}
import React, { Component } from "react";

class Bar extends Component {
  constructor(props) {
    super(props);
    this.state = {
      bar: "bar"
    };
  }

  handleClick = () => {
    this.setState({ bar: "baz" });
  };

  render() {
    const value = this.state.bar;
    return (
      <div>
        <button onClick={this.handleClick}>baz</button>
        <p>{value}</p>
      </div>
    );
  }
}

A couple of things :几件事:

  • Set state in the constructor.在构造函数中设置状态。
  • Use arrow functions (instead of binding in the constructor ... cleaner).使用箭头函数(而不是在构造函数中绑定......更清洁)。
  • Use const when assigning a value that won't change in the function.在分配不会在函数中更改的值时使用 const。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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