反应道具与儿童.什么时候用? [英] React props vs children . What to use when?

查看:39
本文介绍了反应道具与儿童.什么时候用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两种方法有什么区别?

What is the difference between the two approaches ?

将按钮的文本作为道具传递

Passing text for a button as props

   <TextComponent title="Save"/>

    function TextComponent(props){
        return <button>{props.title}<button/>
        }

对比

像孩子一样传递文本

     <TextComponent>Save<TextComponent />

      function TextComponent(props){
          return <button>{props.children}<button/>      
       }

推荐答案

children prop 是当需要在子组件中呈现的内容的结构不固定且受到控制时使用的东西通过呈现它的组件.

children prop is something that you use when the structure of what needs to be rendered within the child component is not fixed and is controlled by the component which renders it.

但是,如果组件的行为在其所有渲染中保持一致,则它可以定义它需要的特定道具,并且父级可以将它们传递给它.

However if behaviour of the component is consistent across all its renders it can define the specific props that it needs and the parent can pass them to it.

一个非常简单的例子可能是一个Navbar,它可以使用children.对于 Navbar,它需要呈现的项目以及顺序或对齐方式或项目取决于它需要如何在不同实例或跨不同页面使用.例如 Navbar 某处可以在一个地方有搜索组件,而在其他地方没有它.此外,有时可能需要左侧的菜单,然后是右侧的登录菜单项和它们之间的搜索栏,有时它们可​​能都出现在没有搜索栏的右侧.在这种情况下,父组件可以控制内部结构如何

A very simple example could be a Navbar which can use children. For a Navbar the items that it needs to render as well as the order or alignment or items depends on how it needs to be used at different instances or across different pages. For instance Navbar somewhere can have Search component at one place and at some other place not have it. Also the menus may sometimes be needed to the left followed by Login menu item to the right and a searchbar between them and sometimes they may all be present to the right without the searchbar. In such cases the parent component can control how the internal structure would be

这篇关于反应道具与儿童.什么时候用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆