如何通过上下文 Api 反应传递状态?

时间:2021-03-11 07:59:55

标签: reactjs react-native

首先我创建了一个 .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'

1 个答案:

答案 0 :(得分:2)

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

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

  const value = [ItemURL, setItemURL];

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