简体   繁体   中英

Use props instead of state

I know if you want to alter something within a component itself you use state, and when the emit is external then u use props to receive it. But today I stumped across this example

var Label = React.createClass({
    handleClick: function(){
        console.log("Click");
        this.props.children = "Text After Click";
        this.setState({liked: false});
    },

    render: function () {
        console.log("Render");
        return (
            <p ref="p" onClick={this.handleClick}>{this.props.children}</p>
            );
    }
});

Used props instead of state to change the text a value of a button. I'm confused now. The link to the source is here http://myshareoftech.com/2013/12/unit-testing-react-dot-js-with-jasmine-and-karma.html

I don't know about the source but when i tried above code it throws this error:

Uncaught TypeError: Cannot assign to read only property 'children' of object # <Object> .

It should not work because the basic property of the props is, as per DOC :

Props are Read-Only, Whether you declare a component as a function or a class, it must never modify its own props. All React components must act like pure functions with respect to their props.

Check the fiddle for error: https://jsfiddle.net/pjnp6yza/

Reference: https://facebook.github.io/react/docs/components-and-props.html#props-are-read-only

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