如何在 JSX 中添加自定义 html 属性 [英] How to add custom html attributes in JSX

查看:39
本文介绍了如何在 JSX 中添加自定义 html 属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这背后有不同的原因,但我想知道如何简单地向 JSX 中的元素添加自定义属性?

There are different reasons behind it, but I wonder how to simply add custom attributes to an element in JSX?

推荐答案

更新以反映 React 16

React 16 原生支持自定义属性.这意味着向元素添加自定义属性现在就像将其添加到 render 函数一样简单,如下所示:

Updated to reflect React 16

Custom attributes are supported natively in React 16. This means that adding a custom attribute to an element is now as simple as adding it to a render function, like so:

render() {
  return (
    <div custom-attribute="some-value" />
  );
}

欲知更多:
https://reactjs.org/blog/2017/09/26/react-v16.0.html#support-for-custom-dom-attributes
https://facebook.github.io/react/blog/2017/09/08/dom-attributes-in-react-16.html

目前不支持自定义属性.有关更多信息,请参阅此未决问题:https://github.com/facebook/react/issues/140

Custom attributes are currently not supported. See this open issue for more info: https://github.com/facebook/react/issues/140

作为一种解决方法,您可以在 componentDidMount 中执行以下操作:

As a workaround, you can do something like this in componentDidMount:

componentDidMount: function() {
  var element = ReactDOM.findDOMNode(this.refs.test);
  element.setAttribute('custom-attribute', 'some value');
}

请参阅 https://jsfiddle.net/peterjmag/kysymow0/ 了解工作示例.(灵感来自 此评论中 syranide 的建议.)

See https://jsfiddle.net/peterjmag/kysymow0/ for a working example. (Inspired by syranide's suggestion in this comment.)

这篇关于如何在 JSX 中添加自定义 html 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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