我正在尝试将一个文件中的值传递给另一个文件。我在实现上下文时遇到问题。无法找出我在这里做错了什么!
import React from 'react'
const Mycontext = React.createContext();
class AppProvider extends React.Component {
constructor(props) {
super(props)
}
render() {
return (< Mycontext.Provider value = {"Hello World"} > {this.props.children}</Mycontext.Provider>)}
}
export const ContextConsumer= Mycontext.Consumer;
我将ContextConsumer导入文件以呈现它。但是我得到一个空白页,代码是否有问题?下面是我的React版本。
“反应”:“ ^ 16.4.2”
import React from 'react'
import {ContextConsumer} from './contxt'
const Display=(props)=>{return(<p>{props.item}</p>)}
const ContextComponent=()=>{
return(
<ContextConsumer>
{(data)=><Display item={data}/>}
</ContextConsumer>
)
}
ReactDOM.render(<ContextComponent/>, document.getElementById("index"));
答案 0 :(得分:1)
您根本没有使用AppProvider
。使用当前的设置,您可能想要这样的东西:
const Mycontext = React.createContext();
class AppProvider extends React.Component {
render() {
return (
<Mycontext.Provider value={"Hello World"}>
{this.props.children}
</Mycontext.Provider>
);
}
}
const Display = (props) => { return (<p>{props.item}</p>) }
const ContextComponent = () => {
return (
<Mycontext.Consumer>
{(data) => <Display item={data} />}
</Mycontext.Consumer>
)
}
ReactDOM.render(<AppProvider><ContextComponent /></AppProvider>, document.getElementById("root"));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>