简体   繁体   English

当通过 map 呈现切换按钮列表时,如何使反应原生切换为 true?

[英]How to make the react native switch to true when list of toggle button is rendered through a map?

Problem:问题:

I am rendering a set of toggle buttons through a map.我正在通过 map 呈现一组切换按钮。 Now I want to make it true or false each when the user is changing the value of each toggle.现在,当用户更改每个切换的值时,我想将其设为真或假。 This is how I have created the toggle component.这就是我创建切换组件的方式。

const AnswerToggle = (props) => {
  const {styles, name} = props;
  return (
    <View style={styles.answerContentContainer}>
      <View style={styles.answerTextContainer}>
        <AppText styles={styles.answerText}>{name}</AppText>
      </View>
      <View style={styles.container}>
        <Switch
          trackColor={{false: '#dddddd', true: '#c1d6ee'}}
          thumbColor={{false: '#ffffff', true: '#007aff'}}
          ios_backgroundColor="#dddddd"
          //   ref={name}
          onValueChange={
            (value) => {
              //   ref[name].value = true;
            }

            // console.log(
            //   '>>>>>> value',
            //   this[`${name}`].value,
            // )
          }
          style={styles.toggle}
        />
      </View>
    </View>
  );
};

And I am loading it through map like this.我正在像这样通过 map 加载它。

return answers.map((answer, i) => {
      return (
        <AnswerToggle
          key={i}
          styles={styles}
          name={name}
        />
      );
    });

I try to do it by giving reference to the Switch component.我尝试通过引用 Switch 组件来做到这一点。 Then It says you cannot use ref without forwardRef so then I put it to the AnswerToggle component but it still giving me the error can some help me to solve this issue?.然后它说你不能在没有 forwardRef 的情况下使用 ref 所以我把它放到 AnswerToggle 组件但它仍然给我错误可以帮助我解决这个问题吗? I tried lot to find out a solution to this problem.我尝试了很多来找到解决这个问题的方法。 But I was unable to do so但我无法这样做

Define the onChange handler in the parent component and pass it in as a prop.在父组件中定义 onChange 处理程序,并将其作为 prop 传入。 When the switch is flipped update the state in the parent accordingly and pass the new value to AnswerToggle as a prop.当开关翻转时,相应地更新父级中的 state 并将新值作为道具传递给 AnswerToggle。

// pseudo code
const [switchValues, setSwitchValues] = useState([]);
const onChange = (index, value) => setSwitchValues( ... );

answers.map((a, i) => <AnswerToggle value={switchValues[i]} onChange={newValue => onChange(i, newValue) />

This will work just fine:这将工作得很好:

const AnswerToggle = (props) => {
  const {styles, name} = props;

  const [toggleStatus, setToggle] = React.useState(false)
  const onChange = () => setToggle(status => !status)

  return (
    <View style={styles.answerContentContainer}>
      <View style={styles.answerTextContainer}>
        <AppText styles={styles.answerText}>{name}</AppText>
      </View>
      <View style={styles.container}>
        <Switch
          trackColor={{false: '#dddddd', true: '#c1d6ee'}}
          thumbColor={{false: '#ffffff', true: '#007aff'}}
          ios_backgroundColor="#dddddd"
          onChange={onChange}
          value={toggleStatus}
          style={styles.toggle}
        />
      </View>
    </View>
  );
};

EDIT:编辑:

If you need to set the statuses of toggles into the parent component, this is my solution for you:如果您需要将切换状态设置为父组件,这是我为您提供的解决方案:

const AnswerToggle = (props) => {
  const {styles, name, onChange, value} = props;

  return (
    <View style={styles.answerContentContainer}>
      <View style={styles.answerTextContainer}>
        <AppText styles={styles.answerText}>{name}</AppText>
      </View>
      <View style={styles.container}>
        <Switch
          trackColor={{false: '#dddddd', true: '#c1d6ee'}}
          thumbColor={{false: '#ffffff', true: '#007aff'}}
          ios_backgroundColor="#dddddd"
          onChange={() => onChange(name)}
          value={value}
          style={styles.toggle}
        />
      </View>
    </View>
  );
};

const Parent = props => {
    // ... other code

    // set all toggles to false
    const [toggleStatuses, setToggle] = React.useState(
        answers.reduce((toggles,answer) => {
            toggles[answer.name] = false
            return toggles
        },{})
    );

    const onChange = name => setToggle(state => ({
        ...state,
        [name]: !state[name],
    }));

    return answers.map((answer, i) => {
        return (
            <AnswerToggle
                value={toggleStatuses[answer.name]}
                onChange={onChange}
                key={i}
                styles={styles}
                name={answer.name}
            />
        );
    });

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM