As discussed in section 6.4 a component instance can be accessed from any configuration option that uses a function by way of the this
keyword. For example, in the code below the this
keyword is used to access the Badge
props
from the component render
configuration option (i.e., this.props.name
).
var Badge = React.createClass({
render: function() {
return <div>{this.props.name}</div>;
}
});
ReactDOM.render(<Badge name="Bill" />, document.getElementById('app'));
Nothing that difficult to grasp is happening if you look at the transformed JavaScript (i.e., JSX to JS)
var Badge = React.createClass({
displayName: "Badge",
render: function render() {
return React.createElement(
"div",
null,
this.props.name
);
}
});
ReactDOM.render(React.createElement(Badge, { name: "Bill" }), document.getElementById('app'));
The { name: "Bill" }
object is sent to the createElement()
function along with a reference to the Badge
component. The value { name: "Bill" }
is set as an instance property value of the component accessible from the props
property (ie. this.props.name === "Bill"
).
- You should consider
this.props
to be readonly, don't set props usingthis.props.PROP = 'foo'
.