gpt4 book ai didi

javascript - 一个简单的 ReactJS 示例来显示警报

转载 作者:行者123 更新时间:2023-11-28 10:38:07 25 4
gpt4 key购买 nike

我是reactjs新手。我使用两个文本框,一个允许用户输入数字并显示其方 block ,另一个允许用户输入用户名,当单击提交按钮时,应该出现一个警报框,说你好用户名。我能够生成正方形,但警报无法正常工作。

这是 HTML 和 CSS:

class EssayForm extends React.Component {
constructor(props) {
super(props);
this.state = {
value: '',
fname:'',
};

this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}

handleChange(event) {
this.setState({value: event.target.value});
this.setState({fname: event.target.fname});
}

handleSubmit(event) {
event.preventDefault();
alert('Hello: ' + this.state.fname);
}

render() {
return (
<div className="example">
<form onSubmit={this.handleSubmit}>
<span>Square of:</span>
<input type="text" value={this.state.value} onChange={this.handleChange} />
<span>First name:</span>
<input type="text" value={this.state.fname} />
<input type="submit" value="Submit" />
</form>
<div className="preview">
<h1>Square of no is</h1>
<div>{this.state.value * this.state.value}</div>
</div>
</div>
);
}
}

ReactDOM.render(<EssayForm />, document.getElementById('app'));
.example {
font-family: 'Open Sans', sans-serif;
display: flex;
padding: 20px;
form {
display: flex;
align-items: flex-start;
margin-right: 50px;
* {
margin-right: 10px;
}
}
h1 {
font-size: 20px;
font-weight: bold;
}
.preview {
white-space: pre;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>

帮助我生成输入用户名的警报框。

最佳答案

您缺少名字的 onChange 处理程序。另外,建议对名字使用另一个 onchange 监听器,因为您不想在更新号码时更新号码值。这是代码的修改版本:

import React from 'react';

export class EssayForm extends React.Component {
constructor(props) {
super(props);
this.state = {
value: '',
fname:'',
};

this.handleChange = this.handleChange.bind(this);
this.handleNameChange = this.handleNameChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}

handleChange(event) {
this.setState({value: event.target.value});
}

handleNameChange(event){
this.setState({fname: event.target.value});

}

handleSubmit(event) {
event.preventDefault();
alert('Hello: ' + this.state.fname);

}

render() {
return (
<div className="example">
<form onSubmit={this.handleSubmit}>
<span>Square of:</span>
<input type="text" value={this.state.value} onChange=
{this.handleChange} />
<span>First name:</span>
<input type="text" value={this.state.fname} onChange=
{this.handleNameChange} />
<input type="submit" value="Submit" />
</form>
<div className="preview">
<h1>Square of no is</h1>
<div>{this.state.value * this.state.value}</div>
</div>
</div>
);
}
}

关于javascript - 一个简单的 ReactJS 示例来显示警报,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57389111/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com