简体   繁体   English

将带有参数的函数传递给子组件并将返回值发送回父组件以存储在 reactjs 中的父状态

[英]Passing a function with a parameter to child component and sending return value back to parent to be stored in parent state in reactjs

Please forgive me, I am new to programming and JavaScript/React...请原谅我,我是编程和 JavaScript/React 的新手...

This is the question from my assignment:这是我作业中的问题:

Make a counter application using React and Node.js.使用 React 和 Node.js 制作一个计数器应用程序。 The user must have the ability to click a button to increase, decrease, or reset a counter.用户必须能够单击按钮来增加、减少或重置计数器。 The app must have the following components: Display, DecreaseCount , IncreaseCount, ResetCount.该应用程序必须具有以下组件:Display、DecreaseCount、IncreaseCount、ResetCount。 Pass the appropriate functions to be used and current counter value to each component.将要使用的适当函数和当前计数器值传递给每个组件。

I'm not sure what the point is of creating components for those simple operations.我不确定为这些简单操作创建组件有什么意义。 I also don't understand what will make those arithmetical components unique if I'm passing them both a function and a value to work on.我也不明白如果我同时传递一个函数和一个值来处理这些算术组件,什么会使它们独一无二。 But I am assuming the point of the assignment is to show that you can pass state to a child, work on it within the child, and then pass the worked-on result back to the parent to be stored in its state.但我假设分配的重点是表明您可以将状态传递给子级,在子级中对其进行处理,然后将处理后的结果传递回父级以存储在其状态中。

Here is the main page, Display.js.这是主页,Display.js。 For now I'm just trying to get the add functionality to work:现在我只是想让添加功能正常工作:

import React, { Component } from 'react';
import IncreaseCount from './IncreaseCount';
import DecreaseCount from './DecreaseCount';
import ResetCount from './ResetCount';

class Display extends Component {
  constructor(props) {
    super(props);

    this.increment = this.increment.bind(this);

    this.state = {
      count: 0
    };
  }

  increment = numToInc => {
    this.setState({ count: numToInc++ });
  };
  decrement = numToDec => {
    this.setState({ count: numToDec-- });
  };
  reset = numToReset => {
    numToReset = 0;
    this.setState({ count: numToReset });
  };

  render() {
    return (
      <div>
        <h2>{this.state.count} </h2>
        <IncreaseCount count={this.state.count} operation={this.increment} />
        <DecreaseCount count={this.state.count} operation={this.decrement} />
        <IncreaseCount count={this.state.count} operation={this.reset} />
      </div>
    );
  }
}

export default Display;

And here is the IncreaseCount component class:这是IncreaseCount 组件类:

import React, { Component } from 'react';

class IncreaseCount extends Component {
  constructor(props) {
    super(props);

    this.state = {
      count: 0
    };
  }

  buttonClick = () => {
    this.setState({ count: this.props.count }); // I am pretty sure this isn't necessary
    this.props.operation(this.state.count);
  };

  render() {
    return <button onClick={this.buttonClick}></button>;
  }
}

export default IncreaseCount;

It is not throwing any errors but is not changing the value of either the Increase count or the Display count properties.它不会抛出任何错误,但不会更改增加计数或显示计数属性的值。 I was expecting both to be changing in lockstep.我原以为两者都会同步变化。 My goal is to send the incremented value back to Display to be displayed.我的目标是将增加的值发送回 Display 进行显示。 Is there a problem with the way I've written and passed my increment function?我编写和传递增量函数的方式有问题吗?

You need to use this.props.count within the IncreaseCount您需要在IncreaseCount使用this.props.count

class IncreaseCount extends Component {
  buttonClick = () => {
    this.props.operation(this.props.count);
  };
  ...
}

A full example might look something like this:一个完整的示例可能如下所示:

class Display extends Component {
  state = {
    count: 0
  };

  increment = numToInc => {
    this.setState({ count: numToInc + 1 });
  };
  decrement = numToDec => {
    this.setState({ count: numToDec - 1 });
  };
  reset = () => {
    this.setState({ count: 0 });
  };

  render() {
    return (
      <div>
        <h2>{this.state.count} </h2>
        <Operation
          name="+"
          count={this.state.count}
          operation={this.increment}
        />
        <Operation
          name="-"
          count={this.state.count}
          operation={this.decrement}
        />
        <Operation
          name="Reset"
          count={this.state.count}
          operation={this.reset}
        />
      </div>
    );
  }
}

class Operation extends Component {
  buttonClick = () => {
    this.props.operation(this.props.count);
  };

  render() {
    return <button onClick={this.buttonClick}>{this.props.name}</button>;
  }
}

Note that you don't have to pass the counter value to each Operation and use a functional setState :请注意,您不必将计数器值传递给每个Operation并使用函数setState

increment = () => {
  this.setState(prev => ({ count: prev.count + 1 }));
};

Using a single component like <Operation /> is certainly how I'd do it.使用像<Operation />这样的单个组件肯定是我的做法。 However, per the requirements of the OP, I'm adding this example that uses all 4 components specified.但是,根据 OP 的要求,我添加了这个使用指定的所有 4 个组件的示例。

import React, { Component } from 'react';

class IncreaseCount extends Component {
  render(props) {
    return <button onClick={this.props.action}>+</button>;
  }
}

class DecreaseCount extends Component {
  render(props) {
    return <button onClick={this.props.action}>-</button>;
  }
}

class ResetCount extends Component {
  render(props) {
    return <button onClick={this.props.action}>reset</button>;
  }
}

class Display extends Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };

    this.increment = this.increment.bind(this);
    this.decrement = this.decrement.bind(this);
    this.reset = this.reset.bind(this);
  }

  increment() {
    this.setState({ count: this.state.count + 1 });
  }

  decrement() {
    if (this.state.count > 0) {
      this.setState({ count: this.state.count - 1 });
    }
  }

  reset() {
    this.setState({ count: 0 });
  }

  render() {
    return (
      <div>
        <h2>{this.state.count}</h2>
        <DecreaseCount count={this.state.count} action={this.decrement} />
        <IncreaseCount count={this.state.count} action={this.increment} />
        <ResetCount count={this.state.count} action={this.reset} />
      </div>
    );
  }
}

export default Display;

This version also prevents the counter from going below 0.此版本还可以防止计数器低于 0。

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

相关问题 将带有函数的参数发送到子组件并返回到父组件 - Sending parameter with function to child component and back to parent component 将存储在子组件内函数中的值传递给 React 中的父组件 - Passing a value stored in a function within a child component to a parent in React 将父级 state 传递给子级并将相同的 state 传回给父级 - Passing parent state to child and passing this same state back to parent ReactJS 将状态从父级传递到子级 - ReactJS Passing state from parent to child ReactJS,将prop从父组件传递到子组件? - ReactJS, passing prop from parent to child component? React:无法通过将函数传递给更新它的子组件来更新父状态 - React: unable to update parent state by passing function to child component that updates it 反应:将 Child1 state 值传递给 Parent 并从 parent 传回 Child2 - React: Passing Child1 state value to Parent and pass back to Child2 from parent ReactJS同时将函数从父级传递给子级并访问父级状态未完全返回 - ReactJS while passing function from parent to child and accessing parent state not returning completely 如何通过在 ReactJS 中将 props 从父组件传递到子组件来初始化状态? - How can i initialize state by passing props from parent component to child component in ReactJS? React,将状态从子组件传递给父组件 - React, passing state from a Child component to the Parent
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM