首页 > 解决方案 > 引发了跨域错误 target.name

问题描述

我正在尝试获取反应组件的属性名称。

看到这个沙箱

这是我的代码sandbox.io

现在,通过传递事件,我可以从按钮获取单击按钮的名称。但我尝试做的是:

      <div>
        <div className={"red"}>red</div>
        <div>not red</div>
        <div name={"red"} className={this.target.name === "red" ? "red" : ""}>
          dynamically allocated red
        </div>
      </div>

我想如果那个 div 的名字是“red”,那个 div 会根据它得到颜色

如何在 react.js 中读取组件的名称属性?

标签: reactjs

解决方案


好的,根据您更新的问题更新了我的答案。

有多种方法可以做到这一点,但我认为最好的方法是创建自己的包含所需逻辑的组件。所以是这样的:

const MyComponent = ({ name, children, ...otherProps }) => {
  return (
    <div name={name} className={name === 'red' ? 'red' : ''} {...otherProps}>
      {children}
    </div>
  );
};

然后你可以像这样在你的渲染函数中使用它:

<MyComponent>this will NOT be red</MyComponent>
<MyComponent name='red'>this one will be red</MyComponent>
<MyComponent name='blue'>this will also NOT be red</MyComponent>

在您使用的示例代码中,this.target.name这是不可能的,仅仅是因为这不是它的工作方式。代码的this那一部分是指当前组件,因此App在您的情况下。该App组件不包含target属性。绑定onClick事件时,函数的第一个参数将是event,该event对象将包含一个target包含 HTML 元素的属性。因此,您可以通过这种方式使用nameHTML 元素的属性。但这仅适用于 onClick 接收此参数。


推荐阅读