简体   繁体   English

React Context - 在消费者内部使用 onClick 设置状态

[英]React Context - setState with onClick inside Consumer

I have implemented React Context API and I am trying to update the state defined inside the Provider via an onClick function inside a child component.我已经实现了 React Context API,并且我正在尝试通过子组件内的 onClick 函数更新 Provider 内定义的状态。

This is what I have done so far, in the App.js I have:这是我到目前为止所做的,在App.js 中我有:

import { createContext } from 'react';
const MyContext = React.createContext();
export class MyProvider extends Component {
    state = {
        currPrj: ''
    }

    handleBtnClick = prjCode => {

        this.setState({
            currPrj: prjCode
        })

    }

    render() {
        return(
            <MyContext.Provider value={{
                state: this.state
            }}>
                {this.props.children}
            </MyContext.Provider>
        )
    }
}

export const MyComsumer = MyContext.Consumer;

Inside my child component I have:在我的子组件中,我有:

import React, { Component } from "react";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
import { MyComsumer } from "../../index";

export class ProjectCard extends Component {

  constructor(props) {
    super(props);

    this.state = {
      // currPrj: ''
    };
  }

  render() {
    return (
      <MyComsumer>
        {(context) => (
          <div className="card card-project">
          <p>{context.state.currPrj}</p>
            <div className="content">
              <div className="author">
                <Link to={ `projects/${this.props.code}/detail/info` } onClick={() => handleBtnClick(this.props.code) }>
                  <h4 className="title">
                    {this.props.title}
                  </h4>
                </Link>
              </div>
          </div>
        )}
      </MyComsumer>
    );
  }
}

export default ProjectCard;

This way I get the following error这样我得到以下错误

Failed to compile
./src/components/ProjectCard/ProjectCard.jsx
  Line 32:  'handleBtnClick' is not defined  no-undef

Search for the keywords to learn more about each error.

I don't get it why, because:我不明白为什么,因为:

<p>{context.state.currPrj}</p>

throws no error...抛出没有错误...

Plus, is this.props.code passed correctly to the function?另外, this.props.code是否正确传递给函数?

Many thanks.非常感谢。

There is linter error because handleBtnClick is not defined.由于handleBtnClick因此存在handleBtnClick错误。 It's a method of another class, not standalone function.它是另一个类的方法,而不是独立的函数。

It's not available in the scope of context consumer function.它在上下文消费者功能范围内不可用。 If consumers are supposed to update the context, updater function should be a part of the context:如果消费者应该更新上下文,updater 函数应该是上下文的一部分:

<MyContext.Provider value={{
    state: this.state,
    update: this.handleBtnClick
}}>

And used like:并使用如下:

context.update(this.props.code)

you can follow this:你可以按照这个:

My Fiddle: https://jsfiddle.net/leolima/ds0o91xa/1/我的小提琴: https : //jsfiddle.net/leolima/ds0o91xa/1/

 class Parent extends React.Component { sayHey(son) { alert('Hi father, this is son '+son+' speaking'); } render() { const children = React.Children.map(this.props.children, (child, index) => { return React.cloneElement(child, { someFunction: () => this.sayHey(index) }); }); return (<div> <b>Parent</b> <hr /> {children} </div>); } } class Child extends React.Component { render() { return <div> <button onClick={() => this.props.someFunction()}>Child</button> </div>; } } ReactDOM.render( <Parent> <Child /> <Child /> </Parent>, document.getElementById('container') );
 <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"></script> <div id="container"> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM