这是关于非标准属性。 https://facebook.github.io/react/docs/tags-and-attributes.html
在反应过程中我做到了这一点:
React.createElement('div', {image:'blah', etc:'blah'});
我需要在image
的元素上设置etc
和setAttribute
,我需要做出反应,在变化时使用智能来维护它。
此处的解决方案https://stackoverflow.com/a/21654914/1828637表示要将其添加到componentDidMount
,但这不是解决方案。当反应框架改变时,该属性将不会被维护。
是否有反应在我的自定义标签上设置属性?
答案 0 :(得分:2)
此解决方案是通过使用React生命周期方法componentWillReceiveProps
来构建链接的答案,以便在每次更改为props时更新DOM元素属性。有关所有生命周期方法的详细信息,请参阅http://facebook.github.io/react/docs/component-specs.html。
(因为componentWillReceiveProps
可以比道具实际更改时更频繁地调用 ,您可能希望在实际在节点上设置它们之前比较道具。)
我提供了你可以玩的小提琴: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>;
}
});
答案 1 :(得分:2)
现在可以使用16个自定义属性
// Your code:
<div mycustomattribute="something" />
// React 15 output:
<div />
// React 16 output:
<div mycustomattribute="something" />
答案 2 :(得分:1)
另一种方法是将属性的名称更改为反应支持的内容(例如data- *属性):
render() {
return (
<div data-image='blah' data-etc='blah' />
);
}
指向其他受支持的属性:https://facebook.github.io/react/docs/dom-elements.html