React,如何将道具转移到子组件

Suppose you have a hierarchy of components, where you pass props from a top component, and you need to pass those props unaltered to a children. It happens many times, and you don’t really want to do like this:

假设您具有组件的层次结构,在其中您从顶部组件传递了道具,您需要将那些不变的道具传递给孩子。 它发生了很多次,而您实际上并不想这样做:

const IntermediateComponent = (props) => {
  return (
    <ChildComponent prop1={props.prop1} prop2={props.prop2} />
  )
}

instead, you want to pass all the props, regardless of their name.

相反,您想传递所有道具,无论其名称如何。

You can do so with the spread operator:

您可以使用点差运算符执行此操作

const IntermediateComponent = (props) => {
  return (
    <ChildComponent {...props} />
  )
}

This syntax is much easier to the eye, much less error prone, and it allows flexibility, since you don’t need to change the props names or add props in the intermediate component when you change them.

这种语法更容易理解,更不容易出错,并且它具有灵活性,因为在更改道具时不需要更改道具名称或在中间组件中添加道具。

翻译自: https://flaviocopes.com/react-pass-props-to-children/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值