gpt4 book ai didi

reactjs - React 上下文消费者呈现多个子级错误

转载 作者:行者123 更新时间:2023-12-04 12:25:34 25 4
gpt4 key购买 nike

我只是尝试使用 react 提供程序,但不知何故我收到此错误:
index.js:1437 警告:上下文使用者呈现有多个子项,或者不是函数的子项。上下文消费者期望一个函数子元素。如果您确实传递了一个函数,请确保它周围没有尾随或前导空格。

这是 context.js

import React, { Component } from 'react'
const Context=React.createContext()
class Providerr extends Component {
state={display:false}
displayeditor=()=>{this.setState({display:!this.state.display}) }
render() { return (
<Context.Provider value={{...this.state,displayeditor:this.displayeditor }}>
{this.props.children}
</Context.Provider>
)
}
}
const Consumer=Context.Consumer
export {Providerr,Consumer}

我想在下面消耗它
import React, { Component } from 'react'
import {NavLink} from "react-router-dom"
import "./leagues.scss"
import {Consumer} from "./context.js"
export default class Navbar extends Component {

render() {
return (
<nav className="navbar navbar-expand-lg">
<a className="navbar-brand" href="#Home">
<img src="./images/customLogo.jpg" className="navlogo"/>
</a>
<div className="collapse navbar-collapse">
<ul className="navbar-nav mx-5">
<NavLink to="/">
<li className="nav-item active mr-5">
<div className="nav-link">
<span>Home</span>
</div>
</li>
</NavLink>
<Consumer> {value =>
<li onClick={value.displayeditor} className="nav-item mr-5">
<div className="nav-link modal_lig" href="">
<span>Leagues</span>
</div>
</li> }
</Consumer>
</nav>
)}}

最佳答案

将整个代码包裹在 Consumer 中如下所示。另请注意,您的某些 html 元素未正确关闭。

    import React, { Component } from 'react'
import {NavLink} from "react-router-dom"
import "./leagues.scss"
import {Consumer} from "./context.js"
export default class Navbar extends Component {

render(){
return(
<Consumer>
{value => (
<nav className="navbar navbar-expand-lg">
<a className="navbar-brand" href="#Home">
<img src="./images/customLogo.jpg" className="navlogo"/>
</a>
<div className="collapse navbar-collapse">
<ul className="navbar-nav mx-5">
<NavLink to="/">
<li className="nav-item active mr-5">
<div className="nav-link">
<span>Home</span>
</div>
</li>
</NavLink>
<li onClick={()=>value.displayeditor()} className="nav-item mr-5">
<div className="nav-link modal_lig" href="">
<span>Leagues</span>
</div>
</li>
</ul>
</div>
</nav>
)}
</Consumer>
)
}
}

关于reactjs - React 上下文消费者呈现多个子级错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55960641/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com