[英]Appending a new dom element in react
I've created a custom component and I want to add child element when the component renders if a certain property is set to be true
. 我已经创建了一个自定义组件,并且如果某个属性设置为
true
则想在该组件呈现时添加子元素。 I used the following code, but the component is not rendered. 我使用了以下代码,但未呈现组件。 what am I doing wrong here.
我在这里做错了什么。
let deleteNode = '';
if(deletable){
deleteNode = '<div />'
}
let defaultClasses = 'chips chips-rounded';
return (
<div className={classNames(classes, defaultClasses)} onClick={ this.onClick }>
{avatar}
<span>{this.props.labelText}</span>
{deleteNode}
</div>
)
You are trying to render a component but actually you are just sending string
in your deleteNode
. 您正在尝试渲染组件,但实际上您只是在
deleteNode
发送string
。 Your code should be something like below 您的代码应如下所示
if(deletable){
deleteNode = (<div />);
}
I different approach would be: 我的不同方法是:
render() {
const defaultClasses = 'chips chips-rounded'
return (
<div className={classNames(classes, defaultClasses)} onClick={ this.onClick }>
{avatar}
<span>{this.props.labelText}</span>
{deletable && <div />}
</div>
)
}
So you don't need the extra if
checking. 因此,
if
检查,则不需要额外的费用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.