React组件间数据传递:切换Switch组件时修改AudienceManage中div文本
Got it, let's get this working smoothly. The core issues with your current setup are twofold: your Switch component isn't triggering the callback you passed from AudienceManage, and you're using direct DOM manipulation instead of React's state system to update the div text—let's fix both.
Step 1: Update the Switch Component to Expose State Changes
First, we need to modify the Switch to let its parent know when its state toggles. We'll add an onChange prop (a more semantic name than onClick for state updates) and call it whenever the switch is clicked, passing the new state value. We'll also update the Props type to include this callback for type safety.
import { useState } from 'react'; type Props = { children?: any; color?: 'primary' | 'success' | 'info'; onChange?: (isChecked: boolean) => void; // Add state change callback }; const Switch = (props: Props) => { const [change, setChange] = useState(false); const handleClick = () => { const newState = !change; setChange(newState); // Notify parent component of the state change if (props.onChange) { props.onChange(newState); } }; let SwitchClass = ''; if (props.color === 'primary') SwitchClass = ' switch-primary'; if (props.color === 'success') SwitchClass = ' switch-success'; if (props.color === 'info') SwitchClass = ' switch-info'; return ( <div className={`switch-box ${change ? SwitchClass : ''}`} onClick={handleClick}> <div className={`switch-inner-box ${change ? ' switch-inner-box-move' : ''}`}></div> </div> ); }; export default Switch;
Step 2: Refactor AudienceManage to Use State for UI Updates
Instead of grabbing the div by ID to update its text, we'll use React's state to control what the div displays. We'll pass our state-updating handler to the Switch's onChange prop to keep everything in sync.
import { useState } from 'react'; import Switch from './Switch'; // Adjust import path as needed import PageContainer from './PageContainer'; // Adjust import path as needed type Props = { /* Add your component props here if needed */ }; const AudienceManage = (props: Props) => { const [isSwitchOn, setIsSwitchOn] = useState(false); // Update local state when the switch toggles const handleSwitchToggle = (newState: boolean) => { setIsSwitchOn(newState); }; return ( <PageContainer> <h1>AudienceManage</h1> {/* Render text based on state instead of manipulating DOM */} <div>{isSwitchOn ? 'ON' : 'OFF'}</div> <Switch onChange={handleSwitchToggle} color='primary' /> <br /> </PageContainer> ); }; export default AudienceManage;
Key Improvements:
- No direct DOM manipulation: We're using React's state system to drive UI updates, which is more predictable and aligns with React's core principles.
- Clear data flow: The
Switchnow explicitly communicates state changes to its parent, making the relationship between components transparent. - Type safety: Updated Props types help catch errors early during development.
内容的提问来源于stack exchange,提问作者Fulano

