[英]Alert content of input box on click of button — React
我在React中編寫了一個簡單的程序,單擊按鈕即可提醒輸入框的內容。 我不能這樣做。 有人可以幫我嗎? 我來自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>
您的代碼有一些問題。 state和alpha函數不應位於render內部,並且您需要初始化狀態並在構造函數中綁定alpha函數,以從類的其余部分訪問它們。 以下重構的代碼應該適合您:
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.