简体   繁体   English

使用 React Hooks 将元素添加到 div

[英]Adding elements to a div using React Hooks

I'm creating a todo list with React and found out that we use states in react unlike innerHTML or appendChild() in Javascript.我正在使用 React 创建一个待办事项列表,并发现我们在反应中使用的状态与 Javascript 中的innerHTMLappendChild()不同。

Here's where I'm facing the problem: When a user clicks a Button, a simple todo is added to the parent Div, and I mean ' Added not Replaced .这就是我面临的问题:当用户单击一个按钮时,一个简单的 todo 会添加到父 Div,我的意思是 ' 已添加而不是已替换

However, when using react hooks useState() , It's just replacing the element, but I want to Add it to the div.但是,当使用反应钩子useState()时,它只是替换元素,但我想将它添加到 div 中。 Here's the code:这是代码:

export default function TodoContainer() {

let [item, setItem] = useState('Nothing to show...');

function handleClick() {
    setItem(item += <TodoItems/>)
}
return (

    <div className="wholeContainer">
        <div className="tododiv">
            <span className="todos">Todos: </span>
            <hr/>
            {item}
        </div>
        <button className="add" onClick={handleClick}>
        <i className="fas fa-plus"></i>
            Add a Todo
        </button>
    </div>
);

} }

So, when using setItem(item + <TodoItem/>) , it just shows: [object Object]因此,当使用setItem(item + <TodoItem/>)时,它只显示: [object Object]

Please help me, I don't know almost nothing about react as I just recently started learning it.请帮助我,我对 react 几乎一无所知,因为我最近才开始学习它。 By the way, the <TodoItems/> returns a div with a todo and its detail inside of it.顺便说一下, <TodoItems/>返回一个 div,里面有一个 todo 和它的细节。

Thanks.谢谢。

Yes, when you item += <TodoItems/> you are appending a JSX literal to a ( possibly ) string, and the result seems to be interpreted as a Javascript object.是的,当您item += <TodoItems/>时,您将 JSX 文字附加到(可能)字符串,结果似乎被解释为 Javascript object。 Objects are not valid JSX and renderable.对象不是有效的 JSX 和可渲染的。

You may want an array of todos for the state, and when adding a new todo add only the data, not the JSX.您可能需要 state 的待办事项数组,并且在添加新待办事项时仅添加数据,而不是 JSX。 When adding a todo to the array you need to create a new array reference and shallow copy the previous state.向数组添加待办事项时,您需要创建一个新的数组引用并浅拷贝之前的 state。 You'll map the state to JSX in the render return.您将 map 和 state 到 JSX 在渲染返回。

Example:例子:

export default function TodoContainer() {
  const [todos, setTodos] = useState([]);

  function handleClick() {
    setTodos(todos => [...todos, "new todo"]);
  }

  return (
    <div className="wholeContainer">
      <div className="tododiv">
        <span className="todos">Todos: </span>
        <hr/>
        {todos.length
          ? todos.map(todo => <TodoItems key={todo} todo={todo} />)
          : 'Nothing to show...'
        }
        </div>
        <button className="add" onClick={handleClick}>
          <i className="fas fa-plus"></i>
          Add a Todo
        </button>
    </div>
  );
}

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

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