作为参考,我有这个StackBlitz Link。您可以检查那里的输出不起作用。
我有一个TodoList Line Item
组件,我想在LineItem
组件内部渲染TodoListLineItem
组件。我正在使用功能组件和带有打字稿的钩子。
<div className="container">
<TodoForm />
<TodoListLineItem>
<LineItem />
</TodoListLineItem>
</div>
如上所示,当我试图将<LineItem />
组件放到<TodoListLineItem>
内时,LineItem组件未呈现在父组件内。
我的问题是如何在父TodoListLineItem组件内部渲染LineItem组件?
答案 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