我要执行以下操作:
function Form(props) {
function SomeFunc(componentName) {
// do something ...
}
return (
<Form name="someForm" >
<SomeComponent name="Long_Name" someProp={SomeFunc("Long_Name")} />
<SomeComponent name="Long_Name" someProp={SomeFunc(this)} /> /* did not work */
<SomeComponent name="Long_Name" someProp={SomeFunc(name)} /> /* did not work */
</Form>
);
}
我想避免多次输入“ Long_Name”。我可以将名称放入变量中,但是该变量会很长,因此我需要在<SomeComponent ... />
声明中多次使用它。
尽管我可以将this
传递到SomeFunc
中,以便可以在函数中使用.name
,但这没用。我还尝试仅传递name
,但也没有用。我希望类似self.name
或self
的概念可以使组件引用其实例。
有没有实现这一目标的方法。
答案 0 :(得分:0)
您可以将 SomeFunc 向下传递给 SomeComponent ,它将可以访问您的组件prop,因此,您可以将传递的带有所需道具的SomeFunc(这是您想要的...对组件的控制。)
注意,即使基于a=a+b
的组件,也不能仅在组件本身中使用this.propName
。如果要使用class
属性,可以按以下说明使用它。
name
如果您想使用 this 关键字,则需要将组件转换为
function Form(props) {
function SomeFunc(arg) {
// do something ...
return arg;
}
return (
<form name="someForm" >
<SomeComponent name="Long_Name" someProp={SomeFunc} />
<SomeComponent name="Long_Name" someProp={SomeFunc} />
<SomeComponent name="Long_Name" someProp={SomeFunc} />
</form>
);
}
function SomeComponent(props) {
// Your render goes here. Just see the way of using props
return (
<div>
<h1>{props.name}</h1>
{/* calling the SomeFunc with name via someProp Property */}
<h2>{props.someProp(props.name)}</h2>
</div>
)
};
组件,因为没有功能组件中class
关键字的含义。
编辑:
如果道具需要某种类型的值,则可以始终创建一个自定义组件,该组件将包装本机组件并按预期提供道具值。
在您的情况下,您可以将this
包装到一个组件中,以确保为您提供预期类型的道具。
答案 1 :(得分:0)
您可以尝试创建组件及其道具的地图,并将其呈现为数组:
const components = new Map([
[SomeComponent1, "Long_Name_1"],
[SomeComponent2, "Long_Name_2"]
]);
return (
<Form name="someForm">
{[...components].map(([Component, name]) => (
<Component name={name} someProp={SomeFunc(name)} />
))}
</Form>
);
也可以以相同的方式使用对象而不是地图。