react自定义属性使用

** 转载文章,原文地址点击这里**

React组件自定义属性的定义及使用

在很多情况下,react组件中,需要使用自定义的属性。也经常需要在默认事件(如,点击onClick)中使用自定义属性。举一个很简单的例子,点击一个按钮,并显示这个按钮“自定义属性”中的string。

import React, { Component } from 'react';
export default MyButton extends Component{
    clickBtn(e){
        console.log(e.currentTarget.getAttribute('data-value'));
    }
    render(){
        return(
            <button onClick={this.clickBtn.bind(this) data-value='Hello World'}>Click Me!</button>
        )
    }
}

此处,在定义和使用自定义属性的时候,有两点需要注意:

  1. 自定义属性的时候,需要使用data-前缀
  2. 使用自定义属性的时候,通过e.currentTarget获取到当前DOM,再通过属性的方式获取

当自定义属性为对象时

当,需要将某个对象,此处称为aimObj,作为组件的属性时,如果直接 data-value={aimObj} 的话,

console.log(e.currentTarget.getAttribute('data-value'));

会得到

[object]

这样的字符串。

可将对象通过JSON.stringify()字符串化后传入data-value,在使用时,再JSON.parse()下就行了

感谢原作者,学到了

猜你喜欢

转载自blog.csdn.net/m0_37148591/article/details/83021724