简体   繁体   中英

React not rendering component

This is my code:

var Item = React.createClass({
    render: function () {
        return (
                React.createElement('div', {},
                        React.createElement('span', {}, this.props.a),
                        React.createElement('span', {}, this.props.b)
                        )
                );
    }
});

var RParent = React.createClass({
    getInitialState: function () {
        return {messages: []};
    },
    addMess: function (data) {
        var self = this;
        self.state.messages.push({
            a: data.a,
            b: data.b
        });
        this.setState({messages: self.state.messages});
    },
    render: function () {
        var messages = this.state.messages;
        return (
                React.createElement('div', {},
                        React.createElement(Item, messages))
                );
    }
});

var box = ReactDOM.render(React.createElement(RParent), document.getElementById('parentDiv'));

function render(a, b) {
    box.addMess({
        a: a,
        b: b
    });
}

Data is sent to the render function. It appears that somehow the properties are not reaching the render function of the Item as they appear to be undefined when I try print them to console.

Any ideas why this might be happening?

The problem is that nothing is rendered into the "parentDiv". It just remains blank. However, on inspecting the elements, I can still see two "span" children under it (which were not created in html or anywhere else except here). But those span elements have no content.

I think there's a fundamental problem to your code. You are trying to pass 'a' and 'b' to your react component through an external function 'render' that seems to be invoking one of the component's functions. This is wrong.

You should pass 'a' and 'b' to your React component RParent as props. Whenever the value of 'a' and 'b' change, your parent component will automatically rerender.

var Item = React.createClass({
render: function () {
    return (
            React.createElement('div', {},
                    React.createElement('span', {}, this.props.a),
                    React.createElement('span', {}, this.props.b)
                    )
            );
}
});

var RParent = React.createClass({
getInitialState: function () {
    return {messages: []};
},
,
render: function () {
    var messages = this.props.messages;
    return (
            React.createElement('div', {},
                    React.createElement(Item, messages))
            );
}
});

ReactDOM.render(
    (<RParent messages= {'a': a, 'b': b} />)
    , document.getElementById('parentDiv'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM