2016-05-05 51 views
1

我一直在使用Web组件(特别是聚合物)一段时间,并且最近一直试图让我的头在React附近。我认为会有相当多的相似之处,尽管我没有看到React以任何方式影响基于它所装载的DOM节点的属性的组件的初始状态。DOM属性和反应

这是可能的,还是我错过了React的意图?能够以这种方式定制组件似乎是使重用更容易的最明显的方法之一。

感谢,

+1

为例,用户将信息传递这样的JavaScript方面的东西。 'ReactDOM.render(,document.querySelector('#root'))'。一旦你已经进入React顶层组件,道具/属性就会正常传递。 – azium

+0

此外,在制作React组件时,您将拥有多个安装节点非常罕见 - 并且HTML仅仅是一种标记语言,因此您无法通过属性真正将html - > javascript中的有意义数据传递给您,就像您在预渲染聚合html视图。它更多地被封装在React中,这实际上是非常好的(当然,如果你希望它是高度可定制的) – azium

回答

0

阵营可以通过this.props访问DOM节点的所有属性。 您可以设置一个阵营组件的状态,以便它反映了初始属性的这样的值:

class MyComponent extends React.Component { 
    constructor(props) { 
    super(props); 
    // here you intialize the state of the component with the value of myAttribute 
    this.state = {myAttribute: props.myAttribute}; 
    } 

    render() { 
    return (
     <div> 
     The value of myAttribute is: {this.state.myAttribute} 
     </div> 
    ); 
    } 
} 

现在,如果你改变了DOM节点的属性,并希望有这种变化反映在状态起反应给你叫componentWillReceiveProps(nextProps)生命周期方法,您可以在更新这样的状态:

class MyComponent extends React.Component { 
    constructor(props) { 
    super(props); 
    // here you intialize the state of the component with the value of myAttribute 
    this.state = {myAttribute: props.myAttribute}; 
    } 

    componentWillReceiveProps(nextProps) { 
    // here you update the state with the new value of myAttribute 
    this.setState({myAttribute: nextProps.myAttribute}); 
    } 

    render() { 
    return (
     <div> 
     The value of myAttribute is: {this.state.myAttribute} 
     </div> 
    ); 
    } 
} 

你可以找到的jsfiddle在这里http://jsfiddle.net/ko2jfqeL/