Yes, that is sort of the difference. Except with the stateful component you can also change the state, using this.setState
for example:
var React = require('react');
var Header = React.createClass({
getInitialState: function() {
return {
imageSource: "mypicture.png"
};
},
changeImage: function() {
this.setState({imageSource: "differentpicture.png"});
},
render: function() {
return(
<img src={this.state.imageSource} onClick={this.changeImage.bind(this)} />
);
}
});
module.exports = Header;
So, in the example above, the changeImage
manages the state of the component (which would also cause all child/dependent components to be re-rendered).
Somewhere in the application, you need to bind data, or remember things. Stateless components are dumb (and that is good), they cannot remember and they cannot give context to other parts of the UI. Stateful components provide the necessary context glue.
On the other hand, stateless components just get passed context (usually through this.props
:
var React = require('react');
var Header = React.createClass({
render: function() {
return(
<img src={this.props.imageSource} />
);
}
});
ReactDOM.render(<Header imageSource="myImage.png"/>, document.body);
In the example above, you can see that during the render
, imageSource
is passed in as an attribute and is then added to the stateless components this.props
object.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…