有一个简单的代码和盒子的例子[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>
我不明白为什么我变得不确定。
2条答案
按热度按时间iovurdzv1#
需要将
Surname
组件中的<h1>{lastName}</h1>
替换为<UserName />
nmpmafwu2#
上下文的基本用法
对子项使用上下文
你读了新的React文档about context,他们肯定会帮助你,干杯