如何将 useState 数据传递给另一个 .tsx 文件?

How to pass useState data to another .tsx file?

我是 React Native 的新手,有人可以帮助我理解和解释如何将数据传递到不同的 .tsx 文件吗?

这是我的一些代码,展示了我正在尝试做的事情。

ToggleSettings.tsx

interface ToggleSettingProps {
  id: string
}

const ToggleSettings = ({
  id
}: ToggleSettingProps) => {
  const [toggled, setToggled] = useState(false);

  return (
   <Box>
     <Switch name={id} isChecked={toggled} onToggle={setToggled} />
   </Box>
  );
};

export default ToggleSettings;

NotificationsScreen.tsx

const ToggleStatus = false; //this property should get the value of toggled from ToggleSettings.tsx

const NotificationsScreen extends React.Component {
 render() {
  return (
   <Box>
     <ToggleSettings
      id={'notif_Main'}
    />
    <Divider marginY="3" />
    {ToggleStatus && ( //As condition to show the other ToggleSettings
      <>
        <ToggleSettings
          id={'notif_DailyFollowUps'}
        />
     </>
    )}
   </Box>
  );
};

基本上,我需要的只是获取 ToggleSettings.tsx 中“toggled”的值,以便将其用作 NotificationsScreen.tsx

中的条件数据

您必须将状态“提升”到 NotificationsScreen 组件。

ToggleSettings.tsx

interface ToggleSettingProps {
  id: string
  isChecked: boolean
  onToggle: (b: boolean) => void
}

// React.FC provides better function component typing
const ToggleSettings: React.FC<ToggleSettingsProps> = ({
  id,
  isChecked,
  onToggle,
}) => (
   <Box>
     <Switch name={id} isChecked={isChecked} onToggle={onToggle} />
   </Box>
);


export default ToggleSettings;

NotificationsScreen.tsx


const NotificationsScreen: React.FC = () =>  {
  const [toggled, setToggled] = useState(false)

  return (
   <Box>
     <ToggleSettings
      id="notif_Main"
      checked={toggled}
      onToggle={setToggled}
    />
    <Divider marginY="3" />
    {toggled && ( //As condition to show the other ToggleSettings
        <ToggleSettings
          id="notif_DailyFollowUps"
        />
    )}
   </Box>
  );
}

由于 React 通过 props 支持父子数据流,我建议您在 Parent (NotificationsScreen) 中定义切换状态,然后将 toggled 和 setToggled 传递给 Child (ToggleSettings)

在NotificationsScreen.tsx

    function NotificationsScreen (){
      const [toggled, setToggled] = useState(false)
      const [otherToggleState, setOtherToggleState] = useState(false);

     render() {
      return (
       <Box>
         <ToggleSettings
          id={'notif_Main'}
          toggled={otherToggleState}
          setToggled={setOtherToggleState}
        />
        <Divider marginY="3" />
        {ToggleStatus && ( //As condition to show the other ToggleSettings
          <>
            <ToggleSettings
     
              id={'notif_DailyFollowUps'}
            />
         </>
        )}
       </Box>
      );
    };

在ToggleSetting.tsx

    const ToggleSettings = (props: ToggleSettingProps) => {

  return (
   <Box>
     <Switch name={props.id} isChecked={props.toggled} onToggle={props.setToggled} />
   </Box>
  );
};

export default ToggleSettings;