gpt4 book ai didi

javascript - ReactJS - 即使字段为空也有新项目

转载 作者:行者123 更新时间:2023-11-30 19:00:36 24 4
gpt4 key购买 nike

我正在练习 React,我正在制作一个 TodoList 组件。但目前,我可以添加一个空的待办事项。我想要一条消息说这是不允许的。

我的问题是即使该字段为空,我也可以创建一个新项目。

这是我的代码:

import React, { Component } from "react";

class TodoList extends Component {
constructor() {
super();
this.state = {
userInput: '',
items: []
};
}

onChange(event) {
this.setState({
userInput: event.target.value
}, () => console.log(this.state.userInput));
}

addTodo(event) {
event.preventDefault();
this.checkField();
this.setState({
userInput: '',
items: [...this.state.items, this.state.userInput] },
() => console.log(this.state.items));
}

deleteTodo(item) {
const array = this.state.items;
const index = array.indexOf(item);
array.splice(index, 1);
this.setState({
items: array
})
}

checkField() {
if(this.state.userInput.length === 0) {

let emptyMessageDom = document.createElement("p");
document.body.appendChild(emptyMessageDom);
emptyMessageDom.innerHTML ="This is empty!!"

}
}

renderTodos() {
return this.state.items.map((item, index) => {
return (
<div key={index}>
{item} {index} | <button onClick={this.deleteTodo.bind(this, item)}>X</button>
</div>)
})
}

render() {
return(
<div>
<form>
<input
value={this.state.userInput}
type="text"
placeholder="New item"
onChange={this.onChange.bind(this)}
required
/>
<button onClick={this.addTodo.bind(this)}>Add</button>
</form>
<div>
{this.renderTodos()}

</div>
</div>
);
}
}

export default TodoList;

我试图将函数checkField()的代码放到addTodo()函数的setState中,但是没有用。

提前致谢!

最佳答案

您应该使用状态来显示错误消息。这将有助于清理呈现和删除消息的方式。 Heres a full working example

更新 addTodo 以根据您的条件有条件地添加。

addTodo(event) {
event.preventDefault();
if (!this.checkField()) {
return
}
this.setState({
userInput: '',
items: [...this.state.items, this.state.userInput]
})
}

然后更新 checkField 以验证并返回一个 bool 值

checkField() {
if(this.state.userInput.length === 0) {
this.setState({error: 'Field is required.'})
return false;
}
return true;
}

然后您可以更新渲染部分以显示错误消息

<form>
<input
value={this.state.userInput}
type="text"
placeholder="New item"
onChange={this.onChange.bind(this)}
required
/>
{!!this.state.error && <label>{this.state.error}</label>}
<button onClick={this.addTodo.bind(this)}>Add</button>
</form>

最后不要忘记在输入发生更改事件时删除错误,因为验证现在已过时。

onChange(event) {
this.setState(
{
userInput: event.target.value,
error: ''
}
);
}

关于javascript - ReactJS - 即使字段为空也有新项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59554840/

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