2016-01-21 80 views
0

这是关于非标准属性。 https://facebook.github.io/react/docs/tags-and-attributes.htmlReactJS中的非标准自定义属性?

在反应我已经做到了这一点:

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

我需要imageetc要在元素上设置有setAttribute,我需要作出反应使用它的智慧,因为它的变化来维护它。

这里的解决方案https://stackoverflow.com/a/21654914/1828637说要将它添加到componentDidMount但这不是一个解决方案。该属性将不会被维护,因为它通过反应框架进行更改。

是否有反正告诉我的自定义标签设置属性?

回答

1

在反应16个自定义属性现在可能

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

// React 15 output: 
<div /> 

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

react 16 custom attributes

2

该解决方案是通过使用React生命周期方法componentWillReceiveProps在链接的答案上构建,以随道具的每次更改更新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>; 
    } 
}); 
+0

哇非常感谢你这么快速的答案,这是高超!它的工作太棒了我更新到'shouldMirrorProps'在你的小提琴的这个叉 - https://jsfiddle.net/Noitidart/wwLcbvfk/ - 你的小提琴帮助我毫无意外!这是一个很好的答案,我希望我能够投票给你更多,所以我喜欢你的其他答案和评论投票给他们。 – Noitidart

+0

这也可以使用'componentWillUpdate'吗?或者只有在计算DOM将会改变时才调用“componentWillUpdate”?因为我在'this.state'中有一些我想要作为属性镜像的东西。 – Noitidart

+1

现在我想到了,在'componentDidUpdate'中执行它可能会更好,因为此时您将知道DOM的任何更改都已被刷新(如果您有一些条件会导致DOM节点离开 - 目前的实现只能工作,因为节点是稳定的)。 [这是另一个小提琴!](https://jsfiddle.net/Lc9Lwpbf/1/) –