简体   繁体   中英

Parameterizing event handlers in React

I am using https://github.com/olahol/react-tagsinput library to create tags in my application. Very weird things are happening when I try to bind renderTag property to a custom function. I think I am missing a point related to JavaScript, not react.

Even though the typeof tagType returns 'string' on component, when I try to render that, it renders [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> + ' | ' <span className="react-tagsinput-tagtype"> {tagType} </span> + ' | ' , the <span>...</span> prints as [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> ) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM