让我困惑的问题是:作为一种约定,我以小写字母开头来为箭头函数组件起一个名字:
const todo = () => {
return (
<div>
</div>
)
}
export default todo
然后,我正在尝试使用'useState'Hook,并出现错误:
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
要成功编译,我需要将组件重命名为'Todo'
在App.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
答案 0 :(得分:1)
导出时命名并不重要。渲染时很重要。 例如:
import todo from './components/todo';
<todo /> // error
相反,相同:
import Todo from './components/todo';
<Todo /> // ok
反应式JSX组件必须大写。