【问题标题】:How to use another function in onPress passed as prop in React Native?如何在 React Native 中使用作为 prop 传递的 onPress 中的另一个函数?
【发布时间】:2023-01-21 03:07:53
【问题描述】:

我有一个可重用的组件AppFormButtonGroup

它接受道具 buttons name value onPress selectedIndex ...props

它还使用const { setFieldValue } = useFormikContext();

它的配置如下:

<ButtonGroup
   buttons={buttons}
   selectedIndex={selectedIndex}
   onPress={onPress}
   {...props}
/>

对于它的应用程序,比如说,在另一个文件上,我这样使用它:

<AppFormButtonGroup
   name="country"
   buttons={countries}
   selectedIndex={selectedCountryIndex}
   onPress={(value) => {
      setCountry(countries[value])
      setSelectedCountryIndex(value)
      setIsCountrySheetVisible(false)
   }}
   value={country}
/>

onPress 道具的内容被传输到 AppFormButtonGroup 然后被应用。目前它正在工作。

我的问题是,如果我已经在另一个文件的 onPress 道具上设置了内容,我该如何在 AppFormButtonGroup 的 onPress 道具中使用 setFieldValue

这是我的目标之一:

AppFormButtonGroup.js

onPress={() => {
   setFieldValue(name, value);
}}

这是按预期工作的,但是它被带有 [下面的代码] 的 onPress 道具覆盖

AnotherFile.js

onPress={(value) => {
      setCountry(countries[value])
      setSelectedCountryIndex(value)
      setIsCountrySheetVisible(false)
   }}

我怎样才能同时使用两者?

我不确定这是我的语法错误还是我正在使用的方法效率很低,如果您能提供更好的方法,我将不胜感激!

谢谢!

我尝试了以下但无济于事:

onPress={[onPress,setFieldValue(name, value)]}

我也尝试在另一个文件上声明和使用 const { setFieldValue } = useFormikContext();,但它似乎不起作用。

我的问题是如何在一个 onPress 中使用以下内容?

setCountry(countries[value])
setSelectedCountryIndex(value)
setIsCountrySheetVisible(false)
setFieldValue(name, value)

setFieldValue(name, value)只能在AppFormButtonGroup.js内部使用

【问题讨论】:

    标签: reactjs react-native


    【解决方案1】:

    在孩子中首先更新本地状态然后调用父处理程序。是这样的:

    const Child = ({onPress}) => { 
      const [count, setCount] = useState(0);
      return <Button
        title={`${count}`}
        onPress={() => {
          setCount(count + 1)
          onPress(count + 1)
        }}
      />
    }
    
    const Parent = () => {
      const [count, setCount] = useState(0);
      return <>
          <Child
            onPress={(c) => setCount(c)}
          />
          <Text>{`Child count ${count}`}</Text>
      </>
    };
    

    【讨论】:

      猜你喜欢
      • 2021-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-15
      • 2022-10-20
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      相关资源
      最近更新 更多