[英]how to check if eles condition in alert in reactjs
in my below code i have one field and one button and without fill the text filed then alert msg is show plz fill the input text.在我下面的代码中,我有一个字段和一个按钮,并且没有填写文本字段,然后警报消息显示请填写输入文本。
right now in my code when i submit the button without input text filled then alert is not show.现在在我的代码中,当我提交未填写输入文本的按钮时,不会显示警报。
How can we do that.我们怎么能这样做。 anybody help me out this.
有人帮我解决这个问题。
My full code https://codesandbox.io/s/staging-microservice-w8bfz我的完整代码https://codesandbox.io/s/staging-microservice-w8bfz
render() {
return (
<div className="App">
Name <input type="text" />
<button className="btn btn-danger" onClick={this.handleClick}>
submit
</button>
</div>
);
}
handleClick = (event) => {
console.log('test')
};
It's quite simple.这很简单。 You need to use a state variable for this.
为此,您需要使用 state 变量。
Explanation:解释:
- I have defined state variable
name
and used that in textbox我已经定义了 state 变量
name
并在文本框中使用它- On change of input value I am assigning input text inside
name
variable在更改输入值时,我在
name
变量中分配输入文本- And then on handleClick, checking whether it's empty or not and based on that showing
alert box
然后在handleClick上,检查它是否为空,并根据显示的
alert box
Working example: Codesandbox工作示例: Codesandbox
constructor(props) {
super(props);
this.state = {
name: ''
};
}
handleClick = () => {
if (!this.state.name) {
alert('Please enter');
}
};
render() {
return (
<div className="App">
Name{" "}
<input
type="text"
value={this.state.name}
onChange={(e) => this.setState({ name: e.target.value })}
/>
<button className="btn btn-danger" onClick={this.handleClick}>
submit
</button>
</div>
);
}
You need to have state inorder to make the input field (name) controlled.您需要拥有 state 才能控制输入字段(名称)。
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
class App extends React.Component {
constructor(props) {
super(props);
this.state = { name: "" };
}
handleClick = (event) => {
if (!this.state.name) {
alert("Name should not be empty !");
}
};
changeHandler = (event) => {
this.setState({ name: event.target.value });
};
render() {
return (
<div className="App">
Name :
<input
id="name"
type="text"
placeholder="Name"
name="aname"
value={this.state.name}
onChange={this.changeHandler}
/>
<button className="btn btn-danger" onClick={this.handleClick}>
submit
</button>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.