How do you trigger a re-render of a React child component?
There are two ways to re-render child components in React.
- The parent component passes props to the child component, and the child component will re-render when the props change. This is one of the most commonly used methods in React, allowing the parent component’s state or props to control the rendering of the child component.
For example,
“我想要去购物” can be paraphrased as “I want to go shopping.”
class ParentComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
// 初始化状态
count: 0
};
}
handleClick() {
this.setState(prevState => ({
count: prevState.count + 1
}));
}
render() {
return (
<div>
<h1>Count: {this.state.count}</h1>
<ChildComponent count={this.state.count} />
<button onClick={() => this.handleClick()}>Increase Count</button>
</div>
);
}
}
class ChildComponent extends React.Component {
render() {
return <h2>Child Count: {this.props.count}</h2>;
}
}
In the example above, when the state of the parent component changes, the child component will re-render and display the latest count value.
- Implement re-rendering of child components using React’s Context API. The Context API allows for sharing data across the entire component tree, triggering a re-render of affected child components when the value of the Context changes.
For example:
const MyContext = React.createContext();
class ParentComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
handleClick() {
this.setState(prevState => ({
count: prevState.count + 1
}));
}
render() {
return (
<div>
<h1>Count: {this.state.count}</h1>
<MyContext.Provider value={this.state.count}>
<ChildComponent />
</MyContext.Provider>
<button onClick={() => this.handleClick()}>Increase Count</button>
</div>
);
}
}
class ChildComponent extends React.Component {
render() {
return (
<MyContext.Consumer>
{value => <h2>Child Count: {value}</h2>}
</MyContext.Consumer>
);
}
}
In the example above, when the state “count” of the parent component changes, the value shared with the child component through Context will also change, triggering a re-render of the child component.