【问题标题】:Passing Props in Context [React]在上下文中传递道具 [React]
【发布时间】:2018-09-02 01:57:27
【问题描述】:

我有 5 代组件结构: A-B-C-D-E

首先我创建一个上下文:

const ThemeContext = React.createContext();

在 A 中创建提供者

     <ThemeContext.Provider value={this.props.name} >
                    <Col><Menu navbarState={this.state.name} /></Col>
    </ThemeContext.Provider>

在 E 中,我需要使用 {this.props.name} 创建上下文

export class Panel extends RoleAwareComponentUser{

    constructor(props) {
        super(props);
        // component will be visible for the roles below:
        this.authorize = ['user'];  
      }

    render(){
    const jsx =(
    <div>
        <ThemeContext.Consumer>
            {value => <Col><Link className={{value: value}} to= "/HomePage">Panel</Link></Col>}
        </ThemeContext.Consumer>
    </div>
      );

      return this.shouldBeVisible() ? jsx : null;

    }
}

Link className 的输出是“[Object, object]”

如何正确传递道具?

【问题讨论】:

  • 顺便说一句,React 开发团队不建议继承组件。相反,您应该使用组合。 reactjs.org/docs/…
  • 嗯,所以如果我在另一个组件中有组件中的组件,不建议这样做?
  • 组件的组合很好。但是在这里,您的组件继承了 RoleAwareComponentUser。
  • 你应该看看高阶组件。
  • 那么提供者值没有被传递,或者props.name 是假的。如果 没有 作为父级,则会发生这种情况。从您发布的代码中不清楚这一点,即 A 和 E 是如何相关的。请提供可以复制您的问题的stackoverflow.com/help/mcve

标签: reactjs


【解决方案1】:

"[Object, object]" 这样的字符串化对象意味着对象值是在需要字符串的地方提供的。

应该是:

<ThemeContext.Consumer>
    {value => <Col><Link className={value} to= "/HomePage">Panel</Link></Col>}
</ThemeContext.Consumer>

className 接受字符串,但如果值为 falsy,则不会添加 class 属性。

正如this answer 中所述,它是ProviderConsumer 组件的层次结构,允许传递上下文,因此&lt;ThemeContext.Consumer&gt; 应该有&lt;ThemeContext.Provider&gt; 作为父级。

如果有适当的层次结构但上下文value 是假的,这意味着this.props.name 在作为提供者value 属性传递时是假的:

<ThemeContext.Provider value={this.props.name}>...

【讨论】:

    猜你喜欢
    • 2021-04-01
    • 2015-07-18
    • 2021-02-17
    • 2018-11-20
    • 2017-04-25
    • 2021-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多