Reactjs 将带有参数的函数传递给react上下文(react native)
在我的代码中,我在App.js文件中声明了这个名为addToArray的方法,并通过如下状态传递给react上下文: App.jsReactjs 将带有参数的函数传递给react上下文(react native),reactjs,react-native,react-context,Reactjs,React Native,React Context,在我的代码中,我在App.js文件中声明了这个名为addToArray的方法,并通过如下状态传递给react上下文: App.js class App extends React.Component { constructor(props) { super(props); this.state = { // init values array: [], ... removeFromArray: () => this.rem
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
// init values
array: [],
...
removeFromArray: () => this.removeFromArray(),
...
}
}
fetchArray = async () => {
...
this.setState({ array: result });
} catch (e) {
alert('Error occured and nothing could be fetched');
}
}
}
componentDidMount() {
this.fetchArray();
...
}
...
removeFromArray = (id) => {
...
alert(id);
}
render() {
// variables to init contexts with
const {
array,
removeFromArray
} = this.state;
return (
<GlobalContext.Provider value={{
array,
removeFromArray
}} >
<Routes />
</GlobalContext.Provider>
);
}
}
export const GlobalContext = React.createContext({
array: [],
removeFromArray: () => { }
});
这就是所谓的:
const btn = (props) => {
const GlobalCtx = useContext(GlobalContext);
return(
<View style={card.editOpacity}>
<Icon
name="minus-circle"
type='font-awesome'
color='red'
onPress={() => {
GlobalCtx.removeFromArray(props.id)
}} />
<Text style={card.header}>{props.title}</Text>
</View>
);
constbtn=(道具)=>{
const GlobalCtx=useContext(GlobalContext);
返回(
{
GlobalCtx.removeFromArray(props.id)
}} />
{props.title}
);
出于某种原因,它不起作用,但我认为它可能与参数以及传递到上下文的方式有关 无需将
removeFromArray
函数放入状态
中。您可以这样呈现提供程序
另外,还不清楚您在添加到状态的函数中添加了什么。removeFromGutka()。谢谢!这就解决了问题。关于
removeFromGutkas()
函数,从代码库复制是一个错误。