问题
I want to pass the value and setValue to Right component . I've done something but it's not working.I am typing but it's deleting immediately.I can't see even what I am typing to textinput.What is the proper way to do this ?
export const Vault = ({ navigation }: VaultStackNavigationProps<"Vault">) => {
const [value, setValue] = useState("");
React.useLayoutEffect(() => {
navigation.setOptions({
headerRight: () => (
<Right
setText={setValue}
value={value}
/>
),
});
}, [navigation]);
return (
//component style
);
};
const Right = ({ value, setText }) => {
const [focus, setFocus] = useState(false);
const { width } = useWindowDimensions();
const onSearch = () => {
setFocus(true);
};
const onClose = () => {
setFocus(false);
};
return (
<>
<Animated.Viewstyle={{flexDirection: "row",justifyContent: "center",alignItems: "center",width:width - 40,
}}
>
{focus && (
<TextInput
value={value}
onChangeText={(text) => setText(text)}
placeholder="Type here"
/>
)}
{value.length > 0 && (
<TouchableOpacity style={{ width: width / 9 }} onPress={onClear}>
<AntDesign name="close" size={24} color="white" />
</TouchableOpacity>
)}
</Animated.View>
{!focus && (
<TouchableOpacity onPress={onSearch} style={{ width: width / 9 }}>
<AntDesign name="search1" size={24} color="#64646E" />
</TouchableOpacity>
)}
</>
);
};
回答1:
Your example code cannot be run without adding more onto it. For future reference, see how to make a minimum, reproducible example.
Anyways, here is an example of passing in the state value and setter method to a child component, which I have tested:
TestComponent.js:
import React, {useState} from "react";
import {TextInput, View, Text, SafeAreaView, StyleSheet} from "react-native";
const TestComponent = props => {
const [value, setValue] = useState("");
return (
<SafeAreaView style={styles.safeAreaView}>
<View style={styles.parent}>
<ChildComponent value={value} setValue={setValue}/>
</View>
</SafeAreaView>
);
};
const ChildComponent = props => {
const textChangeHandler = (text) => {
props.setValue(text);
};
return (
<View style={styles.child}>
<Text>Input Some Text:</Text>
<TextInput
style={styles.input}
value={props.value}
onChangeText={textChangeHandler}
/>
</View>
);
};
const styles = StyleSheet.create({
safeAreaView: {
flex: 1,
},
parent: {
flex: 1,
justifyContent: "center",
alignItems: "center",
},
child: {
flexDirection: "row",
marginHorizontal: 25,
justifyContent: "center",
alignItems: "center",
},
input:{
flex: 1,
marginHorizontal: 10,
borderWidth: 1,
borderColor: "black",
}
});
export default TestComponent;
And here is the App.js file:
import React from 'react';
import {StyleSheet, SafeAreaView} from 'react-native';
import TestComponent from "./TestComponent";
export default function App() {
return (
<SafeAreaView style={styles.safeAreaView}>
<TestComponent />
</SafeAreaView>
);
}
const styles = StyleSheet.create({
safeAreaView: {
flex: 1,
}
});
来源:https://stackoverflow.com/questions/64964992/passing-input-state-from-parent-to-child-component