I'm with some questions on the use of component react. Basically I want to use the "Title" component in various parts of the code, but it always has "states" that vary. I do not quite understand the official documentation on this issue, as I do to inherit this component, and only change the "states" for what I want? I know the question seems silly, but I'm learning and React is very different from everything I saw.
var Title = React.createClass({
displayName: "Title",
getDefaultProps: function () {
return {
className: ""
}
},
render: function () {
return <h1 className={this.props.className}>{this.state.content}</h1>
}
});
-
It seems you shouldn't use state at all. The component should accept its content as children, just like HTML works.Felix Kling– Felix Kling2016年03月23日 13:43:47 +00:00Commented Mar 23, 2016 at 13:43
2 Answers 2
You should use props rather than state in this instance. Props are owned by parents, and state is owned by the component itself. Since you would like to use this component in multiple places, then naturally a parent will decide what the text of the Title should be - therefore props are what you want.
React has a special prop children
, which takes on the value of whatever is passed inside a component's JSX tag.
For instance, here's a mock component which uses your Title component multiple times:
var MyComponent = React.createClass({
render: function() {
return (
<div>
<Title className="foo">Hello</Title>
<Title className="bar">World</Title>
</div>
);
}
});
Since you are now passing text to the component as the children
prop, you must update you Title component to render this:
var Title = React.createClass({
displayName: "Title",
getDefaultProps: function () {
return {
className: ""
}
},
render: function () {
// NOTE: we are now using children prop
return <h1 className={this.props.className}>{this.props.children}</h1>
}
});
A side benefit of this is that you can build more complex titles, containing multiple children, and it will just work:
var MyOtherComponent = React.createClass({
render: function() {
return (
<div>
<Title className="foo">
<span>Hello</span>
<a href="bar.html">World</a>
</Title>
</div>
);
}
});
2 Comments
var text = someCondition ? "Text 1" : Text 2"; return <Title>{text}</Title>;
You might want to replace {this.state.content}
by {this.props.children}
and use your component like this :
<Title className="myclass">my title</Title>
As a general rule, try to avoid using state when possible, dumb component are more easily reusable.