首页 > 解决方案 > 无法有条件地渲染组件

问题描述

我正在尝试根据父状态有条件地渲染组件。但我无法做到这一点。

在我当前的代码中,我可以在“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

标签: reactjs

解决方案


如果其中有一些任务,我认为您想显示待办事项列表

todos.length > 0 ? <TodoList todos={todos} /> : null

或者你可以这样做

{ todos.lenght > 0 && <TodoList todos={todos} /> }

{ true && expression }返回expression { false && expression }返回false


推荐阅读