在 React 中,将所有 props 从父组件传递给子组件是一个好习惯吗? [英] In React, is it a good practice to pass all the props from parent to child component?

查看:32
本文介绍了在 React 中,将所有 props 从父组件传递给子组件是一个好习惯吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个父组件和一个子组件.

Say I have a parent component and one child component.

props 有十个键,但孩子只需要三个.

The props has ten keys, but child needs only three.

将 props 传递给子组件的更好方法是什么?

What is the better way to pass props to child component?

class Parent extends Component {
  render() {
     { /*pass all the ten keys into child*/ }
     <Child {...this.props} />
  }
}

class Parent extends Component {
  render() {
     { /*pass only the needed keys into child*/ }
     <Child key1={key1} key2={key2} key3={key3}/>
  }
}

推荐答案

传递所有的 props 通常不是一个好主意.更多的道具意味着更多的东西会导致子组件不必要地重新渲染.但是,在这些 props 的子集上使用扩展运算符可以很方便.例如,一个父组件可能会收到很多 props,但不会使用其中的大部分,而是将除了一两个之外的所有道具交给子组件.考虑使用 redux-form 之类的示例:

Passing all the props generally isn't a good idea. More props means more things that will cause the child component to unnecessarily re-render. However, it can be convenient to use the spread operator on a subset of those props. For example, a parent component may receive a lot of props, but doesn't use most of them and instead hands all but one or two off to a child component. Consider this example using something like redux-form:

export function Form({ handleSubmit, ...rest }) {
  return (
    <form onSubmit={handleSubmit}>
      <Field name="name" component={FormInput} />  
      <SaveButton {...rest} />
    </form>
  );
}

外部表单组件只关心提交功能.<SaveButton/> 将使用其他指示表单是否脏、有效等的道具来确定是否禁用按钮.

The outer form component only cares about the submit function. Other props indicating whether the form is dirty, valid, etc, would be used by the <SaveButton /> to determine whether or not to disable the button.

这很方便,因为我们不必为不使用它们的组件声明 props.我们只是通过它们.但如前所述,请谨慎使用此模式,确保您了解实际传递的是哪些道具,因为这可能会导致性能问题甚至副作用.

This is convenient because we avoid having to declare props for a component that doesn't use them. We just pass them through. But as stated previously, use this pattern with caution, making sure you're aware of which props you're actually handing down, because it could cause performance issues or even side effects.

事实上,我想说的是,如果您发现自己经常在层次结构中向下传递 props,那么您可能遇到了设计问题,应该更有效地利用您的 redux 存储.

In fact, I'd go so far as to say that if you find yourself passing props down through a hierarchy frequently, you probably have a design problem and should be leveraging your redux store more efficiently.

这篇关于在 React 中,将所有 props 从父组件传递给子组件是一个好习惯吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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