onPress()在expo v42.0.0上不工作.对圆角按钮使用TouchableOpacity



我使用了useState钩子。onSubmitEditing,即按下输入命令setTmpItem应该运行,应该在变量tmpItem中设置inputBox的值。传入的addSubject prop也是一个钩子,可以在第二段代码(app.js)

中看到。但是当我按下RoundedButton时,它既不是控制台记录1也不是2,也不是addSubject(tmpItem)不工作。

Focus.js下面

import React, { useState } from 'react';
import { View, StyleSheet, Text } from 'react-native';
import { TextInput } from 'react-native-paper';
import { RoundedButton } from '../../components/RoundedButton';
export const Focus = ({ addSubject }) => {
const [tmpItem, setTmpItem] = useState(null);
return (
<View style={styles.container}>
<View>
<Text> What would you like to focus on? </Text>
<View>
<TextInput
onSubmitEditing={({ nativeEvent: { text } }) => {
setTmpItem(text);
}}
/>
<RoundedButton
size={50}
title="+"
onPress={() => {
console.log("1");
addSubject(tmpItem);
console.log("2");
}}
/>
</View>
</View>
</View>
);
};

App.js下面

//App.js is the central point to glue everything
import React, { useState } from 'react';
import { View, StyleSheet, Text } from 'react-native';
import { Focus } from './src/features/focus/Focus';
export default function App() {
const [focusSubject, setFocusSubject] = useState(null);
return (
<View>
{focusSubject ? (
<Text>Where am I going to build a timer</Text>
) : (
<Focus addSubject = {setFocusSubject}/>
)}
<Text>{focusSubject}</Text>
</View>
);
}

RoundedButton.js下面

import React from 'react';
import { TouchableOpacity, View, Text, StyleSheet } from 'react-native';
export const RoundedButton = ({
style = {},
textStyle = {},
size = 125,
...props
}) => {
return (
<TouchableOpacity>
<Text>{props.title}</Text>
</TouchableOpacity>
);
};

您需要通过在TextInput组件中传递valueonChangeText道具来处理Focus.jsTextInput,如:

export const Focus = ({ addSubject }) => {
const [tmpItem, setTmpItem] = useState(null);
const onSubmit = () => {
//and handle this onSubmit function the way you want to
//or pass the addSubject props
addSubject(tmpItem);
}
return (
<View style={styles.container}>
<View>
<Text> What would you like to focus on? </Text>
<View>
<TextInput
onChangeText={setTmpItem}
value={tmpItem}
onSubmitEditing={() => onSubmit()}
/>
<RoundedButton
size={50}
title="+"
onPress={() => {
addSubject(tmpItem);
}}
/>
</View>
</View>
</View>
);
};

另外,console.logRoundedButton中不起作用的原因是,您没有将onPressprop传递给RoundedButtonTouchableOpacity。在RoundedButton.js中这样做:

import React from 'react';
import { TouchableOpacity, View, Text, StyleSheet } from 'react-native';
export const RoundedButton = ({
style = {},
textStyle = {},
size = 125,
...props
}) => {
return (
<TouchableOpacity onPress={props.onPress}>
<Text>{props.title}</Text>
</TouchableOpacity>
);
};

props.onPress是你错过的。希望这对你有用。

最新更新