[英]Parameterizing event handlers in React
I am using https://github.com/olahol/react-tagsinput library to create tags in my application. 我正在使用https://github.com/olahol/react-tagsinput库在我的应用程序中创建标签。 Very weird things are happening when I try to bind renderTag property to a custom function.
当我尝试将renderTag属性绑定到自定义函数时,发生了非常奇怪的事情。 I think I am missing a point related to JavaScript, not react.
我想我缺少与JavaScript有关的观点,没有反应。
Even though the typeof tagType returns 'string' on component, when I try to render that, it renders [object Object] | 即使typeof tagType在组件上返回“字符串”,当我尝试呈现它时,它也会呈现[object Object] | hello.
你好。 Why does it render Object?
为什么渲染对象?
defaultRenderTag = (customProps, props) => {
let { tag, key, disabled, onRemove, classNameRemove, getTagDisplayValue, ...other } = props
let { tagType } = customProps;
// This returns 'string'
console.log(typeof tagType)
return (
<span key={key} {...other}>
{/* The type of the tag: */}
{
tagType ? (
// This returns "[object Object] | work"
<span className="react-tagsinput-tagtype"> {tagType} </span> + ' | '
) : null
}
{getTagDisplayValue(tag)}
{!disabled &&
<a className={classNameRemove} onClick={(e) => onRemove(key)} />
}
</span>
)
} }
This is the main component that I use the function above: 这是我使用上述功能的主要组件:
<TagsInput
...
renderTag={this.defaultRenderTag.bind(this, { tagType: 'personal' })}
...
/>
Since you are using string concatenation in JSX <span className="react-tagsinput-tagtype"> {tagType} </span> + ' | '
由于您在JSX中使用字符串连接,因此
<span className="react-tagsinput-tagtype"> {tagType} </span> + ' | '
<span className="react-tagsinput-tagtype"> {tagType} </span> + ' | '
, the <span>...</span>
prints as [Object object]. <span className="react-tagsinput-tagtype"> {tagType} </span> + ' | '
, <span>...</span>
打印为[Object object]。 You can try the below alternative: 您可以尝试以下替代方法:
return ( <span key={key} {...other}> { tagType && <span className="react-tagsinput-tagtype"> {`${tagType} | `} </span> } {getTagDisplayValue(tag)} {!disabled && <a className={classNameRemove} onClick={(e) => onRemove(key)} /> } </span> )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.