Pass new server data to react.js components

后端 未结 3 889
梦如初夏
梦如初夏 2020-12-28 16:14

I\'m new to React.js and struggling to understand few core concepts to decide should we use this library for our application. My main problem is actually handling update in

3条回答
  •  -上瘾入骨i
    2020-12-28 16:54

    If you pass the data as props down to your child component, you can simply update it at a higher level and it will force a render to all components that uses the same property object. Consider this simple example:

    var World = React.createClass({
        render: function() {
            return {this.props.name};
        }
    });
    
    var Hello = React.createClass({
        clickHandler: function() {
            this.setProps({ name: 'earth' });
        },
        render: function() {
            return (
                
    Hello
    ); } });

    Now, when the user clicks the button you change the property on the Hello component, but since you passed the same property (or data) object to the children, they will react to it and update it’s shadow DOM accordingly.

    Here is a fiddle of what I mean: http://jsfiddle.net/xkCKR/

    If you have an external data object, you can just pass it to the top component. Just remember that this doesn’t mean that there is a two-way binding:

    // simple example of a data model
    var Data = { name: 'world' };
    
    var World = React.createClass({
        render: function() {
            return {this.props.data.name};
        }
    });
    
    var Hello = React.createClass({
        clickHandler: function() {
            this.setProps({
                data: { name: 'earth' }
            });
        },
        render: function() {
            return (
                
    Hello
    ); } }); React.renderComponent(, document.body);

    This works because react uses one-way binding of properties. But if say your child component would update it’s properties, it won’t climb up to it’s parent. For that you’ll need the ReactLink add-on or use a pub/sub interface like the one Backbone provides.

提交回复
热议问题