简体   繁体   English

ReactJS中的非标准自定义属性?

[英]Non standard custom attributes in ReactJS?

This is regarding non-standard attributes. 这是关于非标准属性。 https://facebook.github.io/react/docs/tags-and-attributes.html https://facebook.github.io/react/docs/tags-and-attributes.html

In react I have done this: 作为回应,我做到了:

 React.createElement('div', {image:'blah', etc:'blah'});

I need image and etc to be set on the element with setAttribute , and I need react to use its smarts to maintain it as it changes. 我需要使用setAttribute在元素上设置image etc ,并且我需要做出反应以使用其智能功能来更改它。

A solution here https://stackoverflow.com/a/21654914/1828637 says to add it on componentDidMount but this is not a solution. https://stackoverflow.com/a/21654914/1828637上的解决方案说要在componentDidMount上添加它,但这不是解决方案。 The attribute will not be maintained as it changes by the react framework. 该属性将不会被React框架更改,因此将无法维护。

Is there anyway to tell react to set the attribute on my custom tags? 无论如何,有什么办法告诉我在自定义标签上设置属性的反应吗?

In react 16 custom attributes are now possible 在反应中,现在可以使用16个自定义属性

// Your code:
<div mycustomattribute="something" />

// React 15 output:
<div /> 

// React 16 output:
<div mycustomattribute="something" />

react 16 custom attributes 反应16个自定义属性

This solution is to build on the linked answer by using the React lifecycle method componentWillReceiveProps to update the DOM element attributes with every change to props. 该解决方案是通过使用React生命周期方法componentWillReceiveProps来建立链接答案的,以在每次更改prop时更新DOM元素属性。 For more information about all the lifecycle methods, see http://facebook.github.io/react/docs/component-specs.html . 有关所有生命周期方法的更多信息,请参见http://facebook.github.io/react/docs/component-specs.html

(Since componentWillReceiveProps can be called more often than when the props actually change, you may wish to compare the props before actually setting them on the node.) (由于componentWillReceiveProps调用比实际更改道具时调用的频率更高,因此,您可能希望先比较这些道具,然后再将其实际设置在节点上。)

I've provide fiddle you can play with: https://jsfiddle.net/p4h267bo/ and the relevant part of the code is excerpted here: 我提供了小提琴供您使用: https : //jsfiddle.net/p4h267bo/ ,相关代码部分摘录于此:

var Hello = React.createClass({
  componentDidMount() {
    this.mirrorProps(this.props);
  },
  componentWillReceiveProps(nextProps) {
    this.mirrorProps(nextProps);
  },
  mirrorProps(props) {
    var node = ReactDOM.findDOMNode(this);
    node.setAttribute('name', props.name);
  },
  render: function() {
    return <div>Hello {this.props.name}</div>;
  }
});

Another alternative is to change the name of the attribute to something that react supports (such as the data-* attributes) : 另一种选择是将属性名称更改为可响应支持的名称(例如data- *属性):

render() {
    return (
      <div data-image='blah' data-etc='blah' />
    );
}

link to other supported attributes: https://facebook.github.io/react/docs/dom-elements.html 链接到其他受支持的属性: https : //facebook.github.io/react/docs/dom-elements.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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