如何有条件地添加属性以响应DOM元素 [英] How to conditionally add attributes to react DOM element

查看:165
本文介绍了如何有条件地添加属性以响应DOM元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个场景,我使用React.js使用以下代码创建div:

I have a scenario where I'm using React.js to create a div using the following code :

React.createElement('div', {}, "div content") 

一些额外的javascript处理将允许我之后推断出这个div是否需要将className属性设置为ClassA或ClassB,或者它是否应该没有className。

Some additional javascript processing will allow me afterwards to deduce if this div needs to have the className attribute set to" ClassA" or "ClassB" or if it shouldn't have className at all.

javascript中有没有办法访问从React DOM创建的div并添加className属性?

Is there a way in javascript to access the div that was created from the React DOM and to add to it the className attribute?

注意:我无法实现这个是JSX所以我使用了createElement方法。

Note : I couldn't achieve this is JSX so I resorted to the createElement method.

编辑:值得一提的是,我可能需要有条件地添加className以外的属性。例如,我可能需要根据条件逻辑向锚标签添加alt属性。
提前谢谢你。

it is worth to mention that i might need to conditionally add attributes other than className. For example, I might need to add to an anchor tag an "alt" attribute or not based on conditional logic. Thank you in advance.

推荐答案

使用 JSX传播。使用道具构建和对象,根据需要修改它并将其传递给组件,如下所示:

Use JSX spread. Build and object with props, modify it however you like and pass it to component like so:

const props = {
    name: 'SomeName'
}

if (true) {
    props.otherName = 'otherName';
}

return (
    <SomeComponent {...props}/>
);

看到 ... 语法?那个传播操作员可以完成这项任务 - 所有道具最终都会成为你组件的独立属性。

See that ... syntax? That spread operator do the job - all props will end up as separate attributes on your component.

看看这个插件: http://www.webpackbin.com/4JzKuJ9C-

这篇关于如何有条件地添加属性以响应DOM元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆