简体   繁体   English

单击按钮时输入框的警报内容-React

[英]Alert content of input box on click of button — React

I am making a simple program in React to alert the content of input box on the click of a button. 我在React中编写了一个简单的程序,单击按钮即可提醒输入框的内容。 I cannot do that. 我不能这样做。 Can someone help me out please? 有人可以帮我吗? I am from Angular background! 我来自Angular背景!

 class App extends React.Component { render() { this.state = { text1: "hello" } return ( <div> <input type="text" value={this.state.text1}/> <button onClick={alpha}>Click</button> </div> ) alpha(){ alert(this.state.text1); } } } ReactDOM.render(<App/>, document.getElementById('app')); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script> <div id="app"></div> 

You have a few issues with your code. 您的代码有一些问题。 The state and alpha function should not be inside render, and you'll need to initialize your state and bind the alpha function in the constructor to access them from the rest of your class. state和alpha函数不应位于render内部,并且您需要初始化状态并在构造函数中绑定alpha函数,以从类的其余部分访问它们。 The following refactored code should work for you: 以下重构的代码应该适合您:

class App extends React.Component {
  constructor(props) {
      super(props);

      this.state = {
          text1: "hello"
      };

      this.alpha = this.alpha.bind(this);
  }

  alpha() {
    alert(this.state.text1);
  }

  render() {
    return (
      <div>
        <input type="text" value={this.state.text1} />
        <button onClick={this.alpha}>Click</button>
      </div>
    );
  }
}

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

相关问题 如何获取.click按钮以隐藏警报框 - How to get a .click button to hide an alert box 单击按钮时显示 Bootstrap 警报框 - Show Bootstrap alert box on a button click 如果输入框的内容已更改且未按下按钮,如何显示警报消息? - How can I show alert message if input box content is changed and button is not pressed? 点击按钮。 Javascript警告框。 如果单击OK,页面重新加载并需要使用html输入表单值创建php变量 - Click button. Javascript alert box. If click OK, page reloads and need to create php variable with html input form value 如何在反应js中单击按钮时显示警报? - how to show alert on button click in react js? 在 React 中,单击按钮时,显示警报 5 秒,然后隐藏警报 - In React, on button click, display alert for 5 seconds, then hide alert 在按钮上单击确认警告框,查询提交也取消 - on button click with confirm alert box, query submitting on cancel also 单击“提交”按钮时如何在JavaScript警报中回显复选框 - How to echo Check Box in JavaScript Alert When Click on Submit Button 如何在按钮单击后的代码中调用警报框? - how to call an alert box in code behind on button click in? 有可能在警报框按钮单击jQuery中编写页面刷新代码? - it is possible to write a page refresh code in alert box button click in jquery?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM