英文:
I am unable to get the value mapped to a react native Button from onPress, it returns undefined when updating state
问题
我映射了一个数组并设置了Button组件的值和标题。React Native Button的标题被正确渲染并按预期显示。
{fetchedData.map((fetched) => {
return (
<Button title={fetched.PropertyName} value={fetched.PropertyName} onPress={handlePress} />
)
})}
在处理onPress
函数时,我尝试更新应用程序的上下文:
import { PropertyContext } from '../context/PropertyContext';
const { property, setProperty } = useContext(PropertyContext);
const handlePress = async (e) => {
await setProperty(e.target.value); //e.target.title也不起作用
alert(property, "selected");
navigation.navigate('Welcome');
}
e.target.value
和e.target.title
始终返回undefined
。
这是创建的上下文:
import { createContext } from "react";
export const PropertyContext = createContext({ property: null });
export default PropertyContext;
英文:
I mapped through an array and set the value and title of the Button component. The title and of the react native Button is rendered correctly and is displayed as expected.
{fetchedData.map((fetched)=>{
return(
<Button title={fetched.PropertyName} value={fetched.PropertyName} onPress={handlePress} />
)
})}
When handling onPress function I try to update the context of the app:
import {PropertyContext} from '../context/PropertyContext'
const {property, setProperty} = useContext(PropertyContext);
const handlePress = async (e) =>{
await setProperty(e.target.value); //e.target.title doesn't work either
alert(property, "selected");
navigation.navigate('Welcome');
}
The e.target.value and e.target.title always return undefined.
Here is the created context as well:
import {createContext} from "react";
export const PropertyContext = createContext({property: null})
export default PropertyContext;
答案1
得分: 1
const handlePress = async (fetched) => {
// 根据您的应用流程使用获取到的数据
console.log(fetched);
};
{
fetchedData.map((fetched) => {
return (
<Button
title={fetched.PropertyName}
value={fetched.PropertyName}
onPress={() => handlePress(fetched)}
/>
);
});
}
英文:
Unlike on the web, onPress
doesn't dispatch event-related data.
Refactor code as below:
const handlePress = async (fetched) => {
// Use fetched data as per your app flow
console.log(fetched);
};
{
fetchedData.map((fetched) => {
return (
<Button
title={fetched.PropertyName}
value={fetched.PropertyName}
onPress={() => handlePress(fetched)}
/>
);
});
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论