In a React application, you may encounter scenarios where a child component needs to update the parent's state. While props are immutable by default, there are ways to achieve this functionality without using external libraries like Redux.
For child-parent communication, you can utilize a callback function passed as props from the parent to the child. Here's an example:
class Parent extends React.Component { constructor(props) { super(props); this.handler = this.handler.bind(this); } handler() { this.setState({ someVar: 'some value' }); } render() { return <Child handler={this.handler} />; } } class Child extends React.Component { render() { return <Button onClick={this.props.handler} />; } }
In this scenario:
If you're dealing with unrelated components (e.g., Component 5 and Component 3 in your example), you can restructure your components:
This approach allows you to effectively manage state between unrelated components without relying on intermediate state sharing mechanisms.
The above is the detailed content of How Can a Child Component Update a Parent's State in React Without External Libraries?. For more information, please follow other related articles on the PHP Chinese website!