如何在React中引用组件属性或组件本身?

时间:2019-11-05 15:56:46

标签: reactjs

我要执行以下操作:

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.nameself的概念可以使组件引用其实例。

有没有实现这一目标的方法。

2 个答案:

答案 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>
);

也可以以相同的方式使用对象而不是地图。