reactjs 未定义ReactuseContext

dxpyg8gm  于 2022-12-03  发布在  React
关注(0)|答案(2)|浏览(161)

有一个简单的代码和盒子的例子[https://codesandbox.io/s/red-butterfly-kz13ee?file = /src/userName. jsx:0 - 270][1]
我有两个组件,第一个是姓氏,第二个是用户名,我有一个问候语,并试图从组件-〉姓氏导入姓氏,但未定义

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js">

import {createContext, useState} from 'react'

export const lastNameContext = createContext()

const Surname = () => {

  const [lastName, setLastName]= useState('Smith')

  return (<lastNameContext.Provider value={lastName}>
    <h1>{lastName}</h1>
    </lastNameContext.Provider>)

}

export default Surname ;


</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js">

import { useContext} from 'react'
import FirstName from './FirstName'
import Surname, {lastNameContext} from './Surname'

const UserName = () => {
  const lastName = useContext(lastNameContext);
  return (<><h1>{`Hello: ${lastName}`}</h1></>)
}

export default UserName

</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

我不明白为什么我变得不确定。

iovurdzv

iovurdzv1#

需要将Surname组件中的<h1>{lastName}</h1>替换为<UserName />

nmpmafwu

nmpmafwu2#

上下文的基本用法

export const lastNameContext = createContext()

// context value provider
const SurnameContext = (props) => {

  const [lastName, setLastName]= useState('Smith')

  // all children of this component will be able to use the context value

  return (
    <lastNameContext.Provider value={lastName}>
       {props.children}
    </lastNameContext.Provider>)

 // return (<lastNameContext.Provider value={lastName} {...props} />))

}

对子项使用上下文

const UserName = () => {

  const lastName = useContext(lastNameContext);

  return (<><h1>{`Hello: ${lastName}`}</h1></>)
}

// parent providing the children with context
const DisplayNameWithContext  = (props) => {
    return (
        <SurnameContext> 
           // any component at any level will be able to use 
           //   const lastName = useContext(lastNameContext);
           <UserName {...props} />
        </SurnameContext>
    )
}

你读了新的React文档about context,他们肯定会帮助你,干杯

相关问题