让我
困惑的问题是:作为惯例,我从小写字母开始为React 中的箭头函数组件命名:
const todo = () => {
return (
<div>
</div>
)
}
export default todo
然后,我尝试使用"useState"钩子,并出现错误:
Failed to compile.
./src/components/Todo.js
Line 4: React Hook "useState" is called in function "todo" which is neither a React function component or a custom React Hook function react-hooks/rules-of-hooks
为了成功编译,我需要将组件重命名为"待办事项">
在应用程序中.js我像这样使用它:
import Todo from './components/Todo'
这没关系,但是当我使用钩子时,我遇到了错误。命名有什么问题?
UPD
组件的完整代码。我想重命名它 const todo,而不是 const todo。为什么我收到错误?
import React, {useState} from 'react'
const Todo = props => {
const [todoName, setTodoName] = useState('')
const [todoList, setTodoList] = useState([])
// const [todoState, setTodoState] = useState({userInput: '', todoList: []})
const inputChangeHandler = (event) => {
setTodoName(event.target.value)
// setTodoState({
// userInput: event.target.value,
// todoList: todoState.todoList
// })
}
const todoAddHandler = () => {
setTodoList(todoList.concat(todoName))
// setTodoState({userInput: todoState.userInput, todoList: todoState.todoList.contact(todoState.userInput)})
}
return (
<div>
<input type='text' placeholder='Todo' onChange={inputChangeHandler} value={todoName} />
<button onClick={todoAddHandler}>Add todo</button>
<ul>
{todoList.map(todo => (
<li key={todo}>{todo}</li>
))}
</ul>
</div>
)
}
export default Todo
导出时命名无关紧要。渲染时很重要。例如:
import todo from './components/todo';
<todo /> // error
相反,相同:
import Todo from './components/todo';
<Todo /> // ok
React JSX 组件必须大写。