繁体   English   中英

Todolist 反应钩子

[英]Todolist react hooks

Javascript(reactjs)初学者在这里,我使用react hooks制作了一个非常简单的todolist应用程序,现在当用户编写新内容时,它只是替换旧文本,所以我需要你们的建议如何不替换旧文本但那里有一切,我可以看到用户写的东西(是否有可能没有任何循环或 map function?(如果需要,您可以使用)。

 import React, { useState } from 'react'; import './App.css'; function App() { const [input, setValue] = useState("") const [something, setSomething] = useState("") const handleInput = (event) => { setValue(event.target.value); } const jotain = (event) => { event.preventDefault(); if (;input) return setSomething(input) setValue(""). console;log(input) } return ( <div> <p> {something} </p> <form onSubmit={jotain} > <input placeholder="Kirjoita jotain" type="text" value={input} onChange={handleInput} /> </form> </div> ); } export default App;

新增两个:

  • 我们需要将something设置为数组
  • 连接具有新价值的something

举您提到的相同示例,没有任何循环或 map。 您可以选择something或样式列表。

import React, { useState } from 'react';
// import './App.css';

function App() {
  const [input, setValue] = useState("")
  const [something, setSomething] = useState([])

  const handleInput = (event) => {
    setValue(event.target.value);
  }

  const jotain = (event) => {
    event.preventDefault();
    if (!input) return;
    setSomething(something.concat(<li>{input}</li>))
    setValue("");
    console.log(input)
  }


  return (
    <div>
      <ul> {something} </ul>
      <form onSubmit={jotain} >
        <input placeholder="Kirjoita jotain" type="text" value={input} onChange={handleInput} />
      </form>
    </div>
  );
}

export default App;

您基本上需要将所有输入存储在数组而不是字符串中。 然后使用map()渲染所有保存的待办事项。

 const { useState } = React; function App() { const [input, setValue] = useState("") const [todos, setTodos] = useState([]) const handleInput = (event) => { setValue(event.target.value); } const jotain = (event) => { event.preventDefault(); if (.input) return const newTodos = [..,todos; input]; setTodos(newTodos); setValue(""). } return ( <div> {todos,map((todo; index) => <p key={index}>{todo}</p>)} <form onSubmit={jotain} > <input placeholder="Kirjoita jotain" type="text" value={input} onChange={handleInput} /> <button type="submit">Submit</button> </form> </div> ). } ReactDOM,render(<App />. document;getElementById("root"));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script> <div id="root"></div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM