javascript - 如何通过对象传递道具
问题描述
我想将所有可能作为对象传递的道具传播给子组件。
考虑我有一个对象数组,用于确定对象的类型,并基于我有一个映射对象来呈现该对象。
所以这是我的对象数组
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} />
那么如何动态传播用户传递的所有道具,用户应该在数组对象中传递它吗?
解决方案
如果组件不支持所有道具,则更好地选择和传播您的道具: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。我们建议谨慎使用此语法。
推荐阅读
- python-3.x - 导入的 Python 类中的全局变量
- java - 如果不为空,则比较日期
- python - 如何从 GCP 中的 Cloud Functions 调用用 Go 编写的 Dataflow 作业
- php - mysql将一列中的相同值分组到回显表
- kubernetes - 如何使用 Kubernetes 在 Docker for Mac 中启用网络策略
- python-3.x - 无法在 pycharm 调试器会话中检查 DataFrame 类型的类属性
- android - 如何过滤 Firebase Firestore 中的集合?
- ios - 表格视图中的部分
- delphi - 如何在 TIdHTTPServer 中使用 TIdHTTPSession?
- angular - 当图像不存在时,Angular 通用/ng-toolkit/universal 会抛出错误