如何使用参数调用React Context函数

时间:2019-01-14 03:10:51

标签: reactjs

所以我正在尝试做一些非常简单的事情,那就是从上下文组件(位于单独的文件中)使用该函数。

概括地说,从App组件中渲染一个TaskList,并将其包装在Provider中。

当然,在TaskList组件中,使用了Consumer,因此我可以使用其onNewTask来更新Context(提供者)自己的状态。

首先,对于App组件

import React, { Component } from "react";
import TaskList from "./Components/tasklist";
import Grid from "@material-ui/core/Grid";
import { TaskStore } from "./contexts/TasksStore";

class App extends Component {
  render() {
    return (
      <div>
        <Grid item xs zeroMinWidth>
          <TaskStore>
            <TaskList />
          </TaskStore>
        </Grid>
      </div>
    );
  }
}

export default App;

,然后是TaskList组件

import React, { Component } from "react";
import TaskContext from "../contexts/TasksStore";
import Task from "./task";

class TaskList extends Component {
  state = {
    newTask: ""
  };
  renderTasks(tasks) {
    return tasks.map(task => (
      <tr>
        <Task task={task} />
      </tr>
    ));
  }
  onTextChange = el => {
    this.setState({ newTask: el.target.value });
    //console.log(el.target.value);
  };
  render() {
    return (
      <TaskContext.Consumer>
        {({ tasks, onNewTask }) => (
          <div>
            <input type="text" value={this.state.newTask} onChange={this.onTextChange} />

            <button onClick={onNewTask}>Add Task</button>

            <table className="tasklist_container">
              <tbody>{this.renderTasks(tasks)}</tbody>
            </table>
          </div>
        )}
      </TaskContext.Consumer>
    );
  }
}

export default TaskList;

具体来说,我使用 onClick = {onNewTask} 停留在如何将TaskList状态值传递给onNewTask上。我无法在此onClick中完成此操作

这里是我为TaskList设置的提供程序组件(本着替换Redux的精神,我将该组件称为“存储”)

import React from "react";

const Context = React.createContext();

export class TaskStore extends React.Component {
  state = { tasks: ["task1", "task2", "task3", "task4"] };

  onTaskSet = (tasks = []) => {
    this.setState({ tasks: tasks });
  };

  onAddTask = task => {
    const newState = [...this.state.tasks, task];
    this.onTaskSet(newState);
    console.log(newState);
  };

  render() {
    return (
      <Context.Provider value={{ ...this.state, onTaskSet: this.onTaskSet, onNewTask: this.onAddTask }}>
        {this.props.children}
      </Context.Provider>
    );
  }
}

export default Context;

1 个答案:

答案 0 :(得分:1)

以下是传递任务参数的方法:

<button onClick={() => onNewTask(this.state.newTask)}>Add Task</button>

How to update React Context from inside a child component?

还请注意: https://medium.freecodecamp.org/functional-setstate-is-the-future-of-react-374f30401b6b 您应该重写onNewTask

onAddTask = (task) => {
   const setNewState = (oldState) => {
     return {
       tasks: [...oldState.tasks, task]
     }
   }
   this.setState(setNewState);
   console.log(this.state.tasks)
 }