简体   繁体   English

React JS:在父组件内调用子组件方法(与打字稿反应)

[英]React JS : Calling Child component method within parent component (React with typescript)

I am trying to create a custom number picker component and trying to add it to the components wherever it is needed. 我正在尝试创建一个自定义号码选择器组件,并尝试将其添加到需要的任何位置。 But When I am trying to fetch the number picker value in the Parent component , I am getting the older value . 但是,当我尝试在Parent组件中获取数字选择器值时,我得到的是旧值。 Can someone help me with this? 有人可以帮我弄这个吗?

Number Picker Component 数字选择器组件

import * as React from "react";

interface IState {
  value: number;
}

interface IProps {
  setValue(val: number): void;
}

class NumberPicker extends React.Component<IProps, IState> {
  constructor(props: any) {
    super(props);
    this.state = {
      value: 0
    };
  }

  public doDecrement = () =>
    // DECREMENT CODE
    {
      if (this.state.value < 1) {
        console.log("LESS THAN O");
      } else {
        this.setState({
          value: this.state.value - 1
        });
        this.props.setValue(this.state.value);
      }
    };

  public doIncrement = () =>
    // INCREMENT CODE
    {
      this.setState({
        value: this.state.value + 1
      });
      this.props.setValue(this.state.value);
    };

  public handleChange = (
    e: React.ChangeEvent<HTMLInputElement> // CHANGE HANDLER
  ) => {
    const val = parseInt(e.target.value);
    this.setState({ value: val });
  };

  public render() {
    return (
      <div>
        <button
          onClick={this.doDecrement}
          className="fa fa-minus fa-inverse fa-2x"
        />
        <input
          type="text"
          className="number"
          value={this.state.value}
          onChange={this.handleChange}
        />
        <button
          onClick={this.doIncrement}
          className="fa fa-plus fa-inverse fa-2x"
        />
      </div>
    );
  }
}
export default NumberPicker;

PARENT COMPONENT CODE 父母组件代码

import * as React from "react";
import NumberPicker from "./NumberPicker";

interface IState {
  val: number;
}

interface IProps {}

class Parent extends React.Component<IProps, IState> {
  constructor(props: any) {
    super(props);
    this.state = {
      val: 0
    };
  }

  handleVal = (value: number) => {
    this.setState({ val: value }, () => console.log(this.state.val));
  };

  render() {
    return (
      //Some fields along with the below numberpicker
      <NumberPicker setValue={this.handleVal} />
    );
  }
}

export default Parent;

I have tried using setState's callback function as well, but it does not seem to be working . 我也尝试过使用setState的回调函数,但是它似乎不起作用。 Parent component always shows the older value.How will I get the updated value of the NumberPicker inside parent? 父组件始终显示较旧的值。如何获取父内部的NumberPicker的更新值? Help would be appreciated! 帮助将不胜感激!

React's setState is asynchronous, and because of that this.props.setValue function is going to be called before setState has updated your state in child Numberpicker component. React的setState是异步的,因此,在setState更新子Numberpicker组件中的状态之前,将调用this.props.setValue函数。 This is why an old value is passed to the parent component. 这就是为什么将旧值传递给父组件的原因。

Instead you can call this.props.setValue inside setState 's callback function. 相反,您可以在setState的回调函数中调用this.props.setValue

 public doIncrement = () =>
    // INCREMENT CODE
    {
      this.setState({
        value: this.state.value + 1
      }, () => {
              this.props.setValue(this.state.value);
         });

    };
public doDecrement = () =>
    // DECREMENT CODE
    {
      if (this.state.value < 1) {
        console.log("LESS THAN O");
      } else {
        this.setState({
          value: this.state.value - 1
        }, () => {
              this.props.setValue(this.state.value);
           });
      }
    };

setState is not a synchrounous function. setState不是一个同步函数。 So when you are calling the callback from parent you are calling it with old state value, because new value will be set sometime in future. 因此,当您从父级调用回调时,您将使用旧的状态值来调用它,因为新值将在将来的某个时候设置。 You can call the callback with the same value you are setting to state: this.state.value - 1 or this.state.value + 1. It should work as expected. 您可以使用与状态相同的值来调用该回调:this.state.value-1或this.state.value +1。它将按预期工作。 I also recommend to read thinking in react for better intuition about where you should hold your state. 我还建议阅读思考方式,以做出更好的直觉,以了解应该将自己的状态保持在什么位置。

Don't use state for passing values in callback, you can do like:- 不要使用状态在回调中传递值,您可以这样做:-

  handleChange = (
    e: React.ChangeEvent<HTMLInputElement> // CHANGE HANDLER
  ) => {
    const val = parseInt(e.target.value);
    // this.setState({ value: val });
    this.props.setValue(val);
  };

i hope it helps! 希望对您有所帮助!

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

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