React功能组件不会在父功能组件内部变红

时间:2020-08-06 11:04:15

标签: javascript reactjs typescript react-hooks

作为参考,我有这个StackBlitz Link。您可以检查那里的输出不起作用。

我有一个TodoList Line Item组件,我想在LineItem组件内部渲染TodoListLineItem组件。我正在使用功能组件和带有打字稿的钩子。

<div className="container">
      <TodoForm />
      <TodoListLineItem>
          <LineItem />
      </TodoListLineItem>
</div>

如上所示,当我试图将<LineItem />组件放到<TodoListLineItem> 内时,LineItem组件未呈现在父组件内。

我的问题是如何在父TodoListLineItem组件内部渲染LineItem组件?

1 个答案:

答案 0 :(得分:2)

LineItem组件是TodoListLineItem组件的子组件。您需要在LineItem组件内渲染TodoListLineItem组件,以便渲染LineItem组件。

当您将LineItem之类的组件嵌套在TodoListLineItem组件内时,该嵌套组件将作为prop传递给周围的组件,并且可以使用children属性在周围的组件内部进行访问在props对象上。

props.children将是一个数组,其中包含的所有子组件 TodoListLineItem组件。您可以通过在TodoListLineItem组件中渲染props.children来渲染TodoListLineItem的所有子项

const TodoListLineItem: React.FC = (props) =>{
   const [close, setClose] = useState(false);

   return (
     <div>
       <label className="line-item-header"> All Todo List items </label>
       { props.children }       {/* render all the children of TodoListLineItem */}
     </div>
   );
}

演示

https://stackblitz.com/edit/react-ts-asvv7x

您可以在React Docs - Composition vs Inheritance上了解props.children