简体   繁体   中英

React component props value issue

I'm currently learning React, I have a simple component that renders simple plain text. I created a small component where on getting simple plain text from props, but I was surprised. when I assign a simple static value on variable then it's working fine but when I try to get that value from the props, it does not work.

here is sample snippet code.

let TextEditor = React.createClass({
  getInitialState: function () {
    var content = "test 2";
    var content = this.props.plainText
    return {
      content: content
    };
  },

  render() {
    return (
      <div>
        <Editor
          value={this.state.content}
        />
      </div>
    )
  }
})

Advance Thanks for your clue

getInitialState seems a little dated now. I'd recommend at least looking into the ES6 way of doing things. It's also better not to set props to state immediately in your constructor, you could update the state when the component has mounted instead. There are other ways of getting your props into your component so it's working taking a look at the react docs in a bit more detail.

As a basic ES6 example....

class MyComp extends React.Component {
    constructor(props) {
        super(props);
        this.state = { content: '' };
    }

    componentDidMount = () => {
        const { plainText } = this.props;
        this.setState({ content: plainText });
    }

    render() {
        const { content } = this.state;
        return (
            <div>
                <Editor value={content} />
            </div>
        );
    }
}

You can use the following code to achieve the expected result :

class MyComp extends React.Component {
    constructor(props) {
        super(props);
        this.state = { content: this.props.plainText  };
    }
    render() {
        const { content } = this.state;
        return (
            <div>
                <Editor value={content} />
            </div>
        );
    }
}

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