我怎么能调用一些函数,而不使用作为道具接收的onPress


<TouchableOpacity style={styles.clearButton} onPress={clear}>

我想使用使用clear(它是一个函数,从选择器字段清除selectedItem)函数分配给onPress独立。
例如,在某些if条件下,如下所示:

if(someCondition){
// I want to use clear function here.
}

请告诉我怎么做。下面是完整的功能。

function renderField (settings) {
const { getLabel, clear } = settings

if(someCondition){
// I want to use clear function here.
}
return (
<View>

<TouchableOpacity onPress={clear}>
<Text>Clear</Text>
</TouchableOpacity>

<Text>{getLabel(selectedItem)}</Text>

</View>
)
}

整个代码::

import * as React from 'react'
import { Alert, Text, View, TouchableOpacity, StyleSheet } from 'react-native'
import { CustomPicker } from 'react-native-custom-picker'
export default function Test() {
const options = [
{
color: '#2660A4',
label: 'One',
value: 1
},
{
color: '#FF6B35',
label: 'Two',
value: 2
},
]
return (
<View style={{ flex: 1, flexDirection: 'column', justifyContent: 'center' }}>
<CustomPicker
placeholder={'Please select your favorite item...'}
options={options}
getLabel={item => item.label}
fieldTemplate={renderField}
optionTemplate={renderOption}
onValueChange={value => {
Alert.alert('Selected Item', value ? JSON.stringify(value) : 'No item were selected!')
}}
/>
</View>
)
function renderField (settings) {
const { selectedItem, defaultText, getLabel, clear } = settings

/* React.useEffect(() => {
if (selectedItem) {
return
}

clear()
}, [selectedItem, clear]) */
return (

<View style={styles.container}>
<View>
{!selectedItem && <Text style={[styles.text, { color: 'red' }]}>{defaultText}</Text>}
{selectedItem && (
<View style={styles.innerContainer}>
<TouchableOpacity style={styles.clearButton} onPress={clear}>
<Text style={{ color: '#fff' }}>Clear</Text>
</TouchableOpacity>
<Text style={[styles.text, { color: selectedItem.color }]}>
{getLabel(selectedItem)}
</Text>
</View>
)}
</View>
</View>
)
}
function renderOption(settings) {
const { item, getLabel } = settings
return (
<View style={styles.optionContainer}>
<View style={styles.innerContainer}>
<View style={[styles.box, { backgroundColor: item.color }]} />
<Text style={{ color: item.color, alignSelf: 'flex-start' }}>{getLabel(item)}</Text>
</View>
</View>
)
}
}

::参考::

**我的目标:**我想改变选择的值默认基于一些条件,因为我正在实现两个自定义的选择器,所以当第一个选择器的值改变,我想设置第二个选择器的值默认

你想运行一个副作用,

React.useEffect(() => {
if (!someCondition) {
return
}
clear()
}, [someCondition, clear])

最新更新