【问题标题】:onClick method of React Button using JSX使用 JSX 的 React Button 的 onClick 方法
【发布时间】:2023-03-10 03:13:01
【问题描述】:

我开始学习 JS 的基础知识并写了一个小例子来检查按钮在 React 中是如何使用 JSX 工作的,但我觉得这有点令人困惑。

我首先创建一个 React 组件并在构造函数中初始化一个名为 bar 的变量,其值为 'bar'

我希望在按下按钮时将此值更改为 'baz'

我的代码如下所示:

<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>

与我的预期相反,当我在浏览器中加载包含此代码的页面时,会立即显示值 'baz'

很抱歉问了一个可能非常新手的问题,但我不明白为什么会立即显示'baz',而不是在我按下按钮后才显示。感谢您的时间。 :)

【问题讨论】:

  • 我想,你想要onClick={() =&gt; this.baz()}
  • @HoldOffHunger 为什么要使用不必要的 IIFE?这个想法是将函数作为值传递给属性
  • @RafaelHovsepyan:它似乎适用于这种变化。我发布了一个带有代码沙箱的答案。

标签: javascript reactjs jsx


【解决方案1】:

你可以试试这个:

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"));

问题是更新屏幕(DOM)最好改变状态让组件重新渲染。而对于价值最初改变的问题,其他答案很好地解释了它们

【讨论】:

    【解决方案2】:

    您尝试使用函数的方式不正确。请参考以下两种方法之一。另外,在构造函数中将你的函数绑定到这个上下文。

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

    然后

    onClick={this.baz}
    

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

    【讨论】:

    • 请注意,仅传递 {this.baz} 不会为函数提供正确的范围,并且设置 this.bar 将不起作用,除非您以某种方式将范围绑定到函数(使用箭头函数或使用 .bind)
    【解决方案3】:

    我在上面的评论中指出了解决方案,所以,我将进一步讨论该评论......

    你有...

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

    你想要...

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

    我还删除了您的其余代码以产生您想要的结果(“我希望在按下按钮时将此值更改为 'baz'。”)。你还需要...

    this.setState(this);
    

    在此处查看完整的工作示例:

    https://codesandbox.io/s/vj904qy4o0

    【讨论】:

      【解决方案4】:

      baz 立即显示的原因是因为您在点击绑定中调用该函数。您还应该将您的点击处理程序绑定到您的 React 类。下面是一个示例:

      <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>
      

      【讨论】:

      • 或者你可以使用箭头功能摆脱binds handleClick = () =&gt; { this.bar = 'baz'}
      【解决方案5】:

      您在渲染期间调用了baz 函数,这就是更改立即发生的原因:

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

      如果你传递一个函数而不是调用一个函数,那么当按钮被按下时该函数将被调用:

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

      【讨论】:

        【解决方案6】:
        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>
            );
          }
        }
        

        有几件事:

        • 在构造函数中设置状态。
        • 使用箭头函数(而不是在构造函数中绑定...更清洁)。
        • 在分配不会在函数中更改的值时使用 const。

        【讨论】:

          【解决方案7】:

          您需要将值存储在状态中,然后将单击处理程序绑定到组件。然后使用setState() 改变状态的值。当状态改变时,你的组件会重新渲染:

          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>
                  )
                }
          }
          

          【讨论】:

            猜你喜欢
            • 2018-10-31
            • 2016-07-28
            • 2023-03-30
            • 1970-01-01
            • 1970-01-01
            • 2022-11-09
            • 2023-03-12
            • 2020-07-31
            • 1970-01-01
            相关资源
            最近更新 更多