In React, component communication becomes important when you need to update data in one component based on changes in another. There are several ways to approach this, depending on the relationship between the components.
When one component is nested within another, the child component can receive props from the parent. If the child component needs to update the parent, it can use a callback function passed down as a prop.
// Parent component class Parent extends React.Component { handleFilterUpdate = (value) => { // Update the state to apply the filter. this.setState({ filter: value }); }; render() { return ( <Child updateFilter={this.handleFilterUpdate} /> ); } } // Child component class Child extends React.Component { handleFilterChange = () => { // Get the filter value and trigger the parent callback. const value = this.refs.filterInput.value; this.props.updateFilter(value); }; render() { return ( <input type="text" ref="filterInput" onChange={this.handleFilterChange} /> ); } }
When components are siblings, they don't have a direct parent-child relationship. In such cases, you can use a higher-order component (HOC) to wrap both components and provide a communication channel.
// HOC const withFilter = (WrappedComponent) => { class Wrapper extends React.Component { constructor(props) { super(props); this.state = { filter: '' }; } handleFilterUpdate = (value) => { this.setState({ filter: value }); }; render() { return ( <WrappedComponent filter={this.state.filter} updateFilter={this.handleFilterUpdate} /> ); } } return Wrapper; }; // Child components const Component1 = withFilter(({ filter }) => <p>Filter: {filter}</p>); const Component2 = withFilter(({ updateFilter }) => ( <input type="text" onChange={(e) => updateFilter(e.target.value)} /> ));
When components live in separate root components, you can create a global event emitter or a centralized state management solution (e.g., Redux) to facilitate communication. The components subscribe to specific events or actions and respond accordingly.
The above is the detailed content of How Do React Components Communicate with Each Other?. For more information, please follow other related articles on the PHP Chinese website!