javascript - 如何将文本插入到输入中键入的列表中
问题描述
import React, { Component, createElement } from "react";
export default class TodoList extends Component {
state = {
todo: [],
inputValue: "",
};
addTodo = () => {
this.setState({ todo: [...this.state.todo, this.state.inputValue] });
// I want to insert separate paragraph tags (todos from this.state.todo) into the list element here
};
handleKeyDown = (e) => {
if (e.keyCode === 13) {
if (this.state.inputValue === "") return;
this.addTodo();
}
};
handleChange = (e) => {
this.setState({ inputValue: e.target.value });
};
render() {
return (
<div className="list"></div>
<input
type="text"
className="insertTodo"
placeholder="Add a new todo!"
onChange={this.handleChange}
onKeyDown={this.handleKeyDown}
value={this.state.inputValue}
/>
);
}
}
我正在创建一个待办事项列表,用户在其中输入一个输入,然后将待办事项插入到div
with 类list
元素中。我是 React 的新手,所以我不知道我应该采取的最佳方式。
任何帮助表示赞赏,谢谢!
解决方案
您可以map
将数组放在div 中,并通过将每个待办事项包装在标签.list
中来呈现每个待办事项 。p
我添加了一个button
元素来处理该addTodo()
功能。
此外,您可能希望将.list
div 移动到输入下方。
import React, { Component, createElement } from "react";
export default class TodoList extends Component {
state = {
todo: [],
inputValue: ""
};
addTodo = () => {
this.setState({ todo: [...this.state.todo, this.state.inputValue] });
// I want to insert separate paragraph tags (todos from this.state.todo) into the list element here
};
handleKeyDown = (e) => {
if (e.keyCode === 13) {
if (this.state.inputValue === "") return;
this.addTodo();
}
};
handleChange = (e) => {
this.setState({ inputValue: e.target.value });
};
render() {
return (
<div>
<div className="list">
{this.state.todo.map((todo) => {
return <p>{todo}</p>;
})}
</div>
<input
type="text"
className="insertTodo"
placeholder="Add a new todo!"
onChange={this.handleChange}
onKeyDown={this.handleKeyDown}
value={this.state.inputValue}
/>
<button onClick={this.addTodo}>Add Todo</button>
</div>
);
}
}
Codesandbox 链接 - https://codesandbox.io/s/busy-pascal-txh55?file=/src/App.js
推荐阅读
- django - 如何修复“str”对象不是映射错误
- gradle - npm-outdated 的 gradle 等价物是什么?
- regex - 需要我的正则表达式模式以任何顺序在任何提供的文本块中匹配多个术语
- php - CodeIgniter 查询获取位置
- c# - 是否有代码样式选项可以让 Visual Studio 不重新格式化 #pragma 指令?
- mysql - 如何比较选择独特项目的两个结果?
- r - 2个连续变量和一个分类变量
- swift - 在 Xcode 10.2 上的 Swift4.2 中插入 NSManagedObject 后,我会立即收到 Xcode 构建错误
- regexp-substr - 为什么 REGEXP_SUBSTR 读取某些字符(“L”和“RD”)与其他字符不同
- java - 如何创建 n 个子进程,将 m 个元素添加到所有子进程之间的共享列表中?