ReactJS 中的非标准自定义属性



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

在反应中,我已经这样做了:

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

我需要在元素上设置imageetc setAttribute ,我需要 react 使用它的智能来维护它的变化。

这里的解决方案 https://stackoverflow.com/a/21654914/1828637 说将其添加到componentDidMount上,但这不是解决方案。该属性将不会在 react 框架更改时得到维护。

无论如何要告诉反应在我的自定义标签上设置属性吗?

在 react 16 中,现在可以自定义属性

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

反应 16 个自定义属性

此解决方案是使用 React 生命周期方法构建链接答案,componentWillReceiveProps每次更改 props 来更新 DOM 元素属性。有关所有生命周期方法的更多信息,请参阅 http://facebook.github.io/react/docs/component-specs.html。

(由于 componentWillReceiveProps 可以比 props 实际更改时更频繁地调用,因此您可能希望在节点上实际设置它们之前比较 props。

我提供了你可以玩的小提琴: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>;
  }
});

另一种选择是将属性的名称更改为 react 支持的名称(例如 data-* 属性):

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

链接到其他支持的属性:https://facebook.github.io/react/docs/dom-elements.html

最新更新