reactjs - 无法有条件地渲染组件
问题描述
我正在尝试根据父状态有条件地渲染组件。但我无法做到这一点。
在我当前的代码中,我可以在“todos.length>0”之后看到组件,但是当我开始输入任何文本字段时。
我的父组件:
function App() {
const [title,setTitle] = React.useState("")
const [desc, setDesc] = React.useState("")
const [todos, setTodos] = React.useState([])
const titleChange = (e) => {
const value=e.target.value;
setTitle(value)
}
const descChange = (e) => {
const value=e.target.value;
setDesc(value)
}
const handleCancel = () => {
setTitle("");
setDesc("")
}
const handleAdd = () => {
const newTodos = todos;
newTodos.push({
title:title,
description: desc
});
setTodos(newTodos)
}
return (
<div >
<label>Enter Title</label>
<TextField onChange={(e) => titleChange(e)} value={title} />
<label>Description</label>
<TextArea onChange={(e) => descChange(e)} value = {desc}/>
<Button onClick={handleCancel}>Cancel</Button>
<Button onClick={handleAdd}>ADD</Button>
<div>
{todos.length && <TodoList todos={todos} />}
</div>
</div>
);
}
我的子组件:
export default function TodoList (props){
React.useEffect(() => {
console.log("mounted")
})
return (
<div>
{console.log(props)}
</div>
)
}
甚至,我尝试过像这样使用三元运算符,
todos.length ? <TodoList todos={todos} /> : null
解决方案
如果其中有一些任务,我认为您想显示待办事项列表
todos.length > 0 ? <TodoList todos={todos} /> : null
或者你可以这样做
{ todos.lenght > 0 && <TodoList todos={todos} /> }
{ true && expression }
返回expression
{ false && expression }
返回false
推荐阅读
- android - Android Sqlite 根据日期列删除最旧的重复结果
- javascript - Web 应用程序是否应该嵌入到网站的页面中?
- angular - ngFor 删除可观察列表中的重复项
- reactjs - 猫鼬中的文件上传问题
- python - 查找字符串中最长的字母
- python - 如何修复此错误:AttributeError:“numpy.ndarray”对象没有属性“apply”
- java - 空字符串是否在 Java 中分配了内存?
- javascript - Insert items matching data attribute to ID's with jQuery
- vue.js - 即使从应用程序外部输入数据,也不会反映
- android - 为什么在这个自定义版本的 android 中有些 UI 按钮是可点击的,而另一些是不可点击的?