首页 > 解决方案 > 如何通过对象传递道具

问题描述

我想将所有可能作为对象传递的道具传播给子组件。

考虑我有一个对象数组,用于确定对象的类型,并基于我有一个映射对象来呈现该对象。

所以这是我的对象数组

const inputFields = [
  {
    key: 'images',
    type:'otp', 
    label: "Upload all your images", 
    required: true, 
    helper: 'You can change your profile pic anytime from settings', 
    templateOptions:{
      noOfTextInput:5
    }
  }, 
  {
    key: 'name', 
    type: 'text', 
    label: `Your Full Name`,
    helper: 'Using your real name would make it more likely for you to get a match',
    required: true,
    templateOptions: { 
      placeHolder: 'Frank Murphy',
      templateStyle: styles.textStyle // refer to the style component
    }
  }]

这里 typeimage表示,我希望image组件渲染, typetext表示我希望 typeTextinput渲染

现在Textinput可以采用许多我想在我的 TextInput 组件上传播的道具(许多道具,我的意思是它支持的所有道具)

  <TextInput  
      style={[{color: defaultColor, borderColor: defaultColor}, styles.defaultTextInputStyle, textInputStyle]}
      onChangeText={text => onChangeHandler(text)}
      keyboardType
      value={value} />

那么如何动态传播用户传递的所有道具,用户应该在数组对象中传递它吗?

标签: javascriptreactjs

解决方案


如果组件不支持所有道具,则更好地选择和传播您的道具:TextInput

const textInputFieldProps = {label: "my Name", required: true, notThis: "nono"};

const Comp = () => {
  // destructure all props for TextInput (here label and required)
  const { label, required, ...rest } = textInputFieldProps;
  // and spread them into TextInput
  return  <TextInput {...{ label, required }} />
};

您可以另辟蹊径,将其余分配用于所有需要的道具:

const Comp2 = () => {
  const { notThis, ...rest } = textInputFieldProps;
  return  <TextInput {...rest} />
};

我赞成第一个,因为在传递到TextInput. 想象一下,您添加了更多道具,这些道具也将通过 传播rest,而您可能不想要这个。

React 文档如何传播属性:

扩展属性可能很有用,但它们也可以轻松地将不必要的道具传递给不关心它们的组件或将无效的 HTML 属性传递给 DOM。我们建议谨慎使用此语法。


推荐阅读