【问题标题】:React Native - Sets the state of the child component directly on the parent componentReact Native - 直接在父组件上设置子组件的状态
【发布时间】:2021-03-21 10:53:51
【问题描述】:

我想问一个问题。在我遇到的情况下,我有很多内部使用状态的组件。所以我没有在父组件中声明组件的状态,因为我不希望父组件看起来有多个状态。我的问题是我可以在父组件中设置每个子组件的状态值吗?

这是我想要做的代码示例:

import React from 'react';
import {Switch} from 'react-native';

const Parents = () => {
  {/**
    Can I set state (setIsEnabled) directly on the parent component?

    For example:
    <Child active={true} onValueChange={() => setIsEnabled(!isEnabled)} />
  */}
  return (
    <Child active={true} />
  );
}

const Child = ({active}) => {
  const [isEnabled, setIsEnabled] = React.useState(active);

  return (
    <Switch
      trackColor={{
        false: 'rgba(0, 0, 0, 0.12)',
        true: 'rgba(66, 133, 244, 0.54)',
      }}
      thumbColor={isEnabled ? 'rgb(66, 133, 244)' : 'rgb(250, 250, 250)'}
      ios_backgroundColor="rgba(0, 0, 0, 0.12)"
      onValueChange={() => setIsEnabled(!isEnabled)}
      value={isEnabled}
    />
  );
}

【问题讨论】:

    标签: javascript reactjs react-native components state


    【解决方案1】:

    我猜这就是你要找的东西

    import React from 'react';
    import {Switch} from 'react-native';
    
    const Parents = () => {
      {/**
        Can I set state (setIsEnabled) directly on the parent component?
    
        For example:
        <Child active={true} onValueChange={() => setIsEnabled(!isEnabled)} />
      */}
      return (
        <Child active={true} />
      );
    }
    
    const Child = (props) => {
      const [isEnabled, setIsEnabled] = React.useState(props.active);
    
      return (
        <Switch
          trackColor={{
            false: 'rgba(0, 0, 0, 0.12)',
            true: 'rgba(66, 133, 244, 0.54)',
          }}
          thumbColor={isEnabled ? 'rgb(66, 133, 244)' : 'rgb(250, 250, 250)'}
          ios_backgroundColor="rgba(0, 0, 0, 0.12)"
          onValueChange={() => setIsEnabled(!isEnabled)}
          value={isEnabled}
        />
      );
    }
    

    【讨论】:

      猜你喜欢
      • 2020-10-06
      • 2021-12-27
      • 2020-12-14
      • 1970-01-01
      • 2017-12-06
      • 2021-03-14
      • 1970-01-01
      • 1970-01-01
      • 2015-05-19
      相关资源
      最近更新 更多