[英]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.