reactjs - 引发了跨域错误 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 中读取组件的名称属性?
解决方案
好的,根据您更新的问题更新了我的答案。
有多种方法可以做到这一点,但我认为最好的方法是创建自己的包含所需逻辑的组件。所以是这样的:
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 元素的属性。因此,您可以通过这种方式使用name
HTML 元素的属性。但这仅适用于 onClick 接收此参数。
推荐阅读
- nginx - 从 nginx 到 Angular 应用程序的代理传递问题
- jenkins - 并行詹金斯作业,读取多个文件和错误
- android - Flutter 中是否有任何受静音模式影响的音频/声音包?Android 和 iOS
- python - Sentinel-2:如何从纬度/经度地理坐标中了解 S2 瓦片?
- java - 如何在 Kotlin 中为变量分配不同的类型并用它调用函数?
- node.js - Puppeteer webscraping html 的缺失部分
- java - 无法在 Android 11 中创建文件夹(目录),如何创建?
- flutter - 有没有办法检测何时将小部件添加到树中?
- flutter - 如何在同一个底页中打开一个新屏幕?
- json - 如何将列表转换为 json?