【发布时间】:2020-07-14 18:47:07
【问题描述】:
我是React.js 的初学者,我对 React 中的组件有点困惑,我们可以只将组件的代码作为回报而不是制作组件,这里我有(简单的待办事项列表)两个代码一个工作正常,但第二个我稍微改变了它,但它不工作,或者我做错了?
这里是 1:
import React, { useState } from 'react';
import './App.css';
function Todo({ tod, index }) {
return <div className="todo">{tod.text}</div>
}
function TodoForm({ addTodo }) {
const [value, setValue] = useState('');
return (
<form>
<input
type="text"
className="input"
value={value}
placeholder="Add Todo..."
onChange={e => setValue(e.target.value)}
/>
</form>
)
}
function App() {
const [todos, setTodos] = useState([
{
text: ' Learn about react',
isCompleted: false
},
{
text: ' Learn about react',
isCompleted: false
},
{
text: ' Learn about react',
isCompleted: false
}
]);
const addTodo = text => {
const newTodos = [...todos, { text }];
setTodos(newTodos);
}
return (
<div className="app">
<div className="todo-List">
{todos.map((todo, index) =>
<Todo key={index} index={index} tod={todo} />
)}
<TodoForm addTodo={addTodo} />
</div>
</div>
)
}
export default App;
下面是我如何通过从函数 TodoForm 中获取所有内容并将其放入 return 2 来更改该代码:
import React, { useState } from 'react';
import './App.css';
function Todo({ tod, index }) {
return <div className="todo">{tod.text}</div>
}
const [value, setValue] = useState('');
function App() {
const [todos, setTodos] = useState([
{
text: ' Learn about react',
isCompleted: false
},
{
text: ' Learn about react',
isCompleted: false
},
{
text: ' Learn about react',
isCompleted: false
}
]);
const addTodo = text => {
const newTodos = [...todos, { text }];
setTodos(newTodos);
}
return (
<div className="app">
<div className="todo-List">
{todos.map((todo, index) =>
<Todo key={index} index={index} tod={todo} />
)}
<form>
<input
type="text"
className="input"
value={value}
placeholder="Add Todo..."
onChange={e => setValue(e.target.value)}
/>
</form>
</div>
</div>
)
}
export default App;
我希望第二个代码像第一个代码一样工作,所以我删除了组件并将其代码作为回报。
这是我遇到的一个错误:
react.development.js:1465 Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
【问题讨论】:
-
能否请您格式化一下您提供的代码?另外,我不确定您的问题到底是什么。
-
请告诉我们如何它“不工作”
标签: javascript css reactjs function jsx