I have 2 nested components:
class Component1 extends React {
constructor(props) {
super(props);
this.state = {
person: {
name: "Genaro",
age: 125
}
};
}
render() {
return (
<SubComponent
person={this.state.person}
/>
);
}
}
Now, I want It to render SubComponent
when my parent class' state changes. This is done automatically by React, but I can do it in two ways:
Option 1 (with state):
class SubComponent extends React {
constructor(props) {
super(props);
this.state = {
person: props.person
};
}
componetWillReceiveProps(props) {
this.setState({ person: props.person });
}
render() {
return (
<h1>Name: {this.state.person.name}</h1>
);
}
}
Option 2 (with instance variables):
class SubComponente extends React {
constructor(props) {
super(props);
this.person = props.person;
}
componetWillReceiveProps(props) {
this.person = props.person;
}
render() {
return (
<h1>Name: {this.person.name}</h1>
);
}
}
I only can use a class (I need to call a lot of instance methods). That's why I can't do this (the cleaner way):
function SubComponent(props) {
return (
<h1>Name: {props.person.name}</h1>
);
}
Both of them work, but:
I couldn't find an example in this context.
Thanks in advance and sorry about my English
As I tried to explain in my comment, you don't need to do anything to render your Subcomponent
. A child component rerenders if its props change via the parent component. So, do not set its props to a state, instead use props directly.
class Component1 extends React.Component { constructor(props) { super(props); this.state = { person: { name: "Genaro", age: 125 } }; } handleChange = e => { const { target } = e; this.setState( prevState => ({ person: { ...prevState.person, name: target.value } }) ) } render() { return ( <div> <p>Change name</p> <input onChange={this.handleChange} /> <SubComponent person={this.state.person} /> </div> ); } } class SubComponent extends React.Component { render() { return ( <h1>Name: {this.props.person.name}</h1> ); } } ReactDOM.render(<Component1 />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="root"></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.