reactjs 在React Native中传递函数作为 prop

ogsagwnx  于 2023-03-01  发布在  React
关注(0)|答案(2)|浏览(157)

如何使用navigation.navigate将setter函数(useState)作为prop传递?我将它设置为:

const [firstName, setfirstName] = useState('');
  const [dob, setDOB] = useState('');
  const [medicalConditions, setMedicalConditions] = useState('');
  const [allergies, setAllergies] = useState('');
  const [bloodtype, setBloodtype] = useState('');
  const [height, setHeight] = useState('');
  const [weight, setWeight] = useState('');
  return (
    <KeyboardAvoidingView style={styles.container} behavior="padding">
        <View style={styles.buttonContainer}>
          <TouchableOpacity
          onPress={() => navigation.navigate('Profile', {
            setMedicalConditions: (a) => setMedicalConditions(a),
            setAllergies: (b) => setAllergies(b),
            setBloodtype: (c) => setBloodtype(c),
            setHeight: (d) => setHeight(d),
            setWeight: (e) => setWeight(e)
          })}
          style={[styles.button, styles.buttonOutline]}>
            <Text style={styles.buttonText}>Edit</Text>
          </TouchableOpacity>
        </View>
      </View>
    </KeyboardAvoidingView>
  )

它工作正常,但我得到一个错误说:

Non-serializable values were found in the navigation state. Check:

Profile > params.setMedicalConditions (Function)

This can break usage such as persisting and restoring state. This might 
happen if you passed non-serializable values such as function, class 
instances etc. in params. If you need to use components with callbacks in 
your options, you can use 'navigation.setOptions' instead. See 
https://reactnavigation.org/docs/troubleshooting#i-get-the-warning-non-
serializable-values-were-found-in-the-navigation-state for more details.

我尝试使用DeviceEventEmitter,但它表示已弃用。

5kgi1eie

5kgi1eie1#

不能将带有navigate的setter函数传递给其他组件
你需要做的是创建一个函数来更新你的状态,例如:

const updateAllergies = (newValue) => {
   setAllergies(newValue);
}

现在,您可以传递此函数,并从子组件使用它来更新父组件中的allergies状态。

3pmvbmvn

3pmvbmvn2#

您必须在屏幕A中创建函数X(包含setter)并传递到屏幕B。当您在屏幕B中调用函数X时,setter也会被调用。

const functionX = (newValue) => {
   setHeight(newValue);
   }

以及

>  navigation.navigate('Profile', {
>         setHeight: (d) => functionX(d),  
>       })}

如果只想保存值,请使用**useRef()**insted

相关问题