首页 > 解决方案 > 如何通过上下文 Api 反应传递状态?

问题描述

首先,我创建了一个 .js 文件并创建了上下文。

在 app.js 中

export default function App({ navigation }) {
    const [ItemURL,setItemURL] = useState('URL')

    return (
        <ItemContext.Provider value={ItemURL}>
            ...
        </ItemContext.Provider>
    )
}

现在我想将我的传递setItemURL给我的子组件

所以我尝试了。

export default const ItemsComponent = (props) => {
    const [URL, setURL] = useContext(ItemContext)
    return(
       <TouchableWithoutFeedback
                onPress={() => {
                    setURL(props.Json.Image)
                }}
            />
    )
}

但它不起作用并且说setURL is not a function(in setURL(props.Json.Image)) ,setURL is 'R'

标签: reactjsreact-native

解决方案


您实际上也应该setURL在上下文值中传递函数。

export default function App({ navigation }) {
  const [ItemURL, setItemURL] = useState('URL');

  const value = [ItemURL, setItemURL];

  return (
    <ItemContext.Provider value={value}>
      ...
    </ItemContext.Provider>
  )
}

推荐阅读