TypeError:无法使用事件读取未定义的属性“ setState”

时间:2019-06-26 06:58:31

标签: javascript reactjs typescript

我在将值从子组件传递到父state时遇到麻烦。在TypeError: Cannot read property 'setState' of undefined

中输入值后,给出的错误是input
interface InterfaceState {
  password: string;
}

class Parent extends Component<InterfaceState> {
  private static INITIAL_STATE = {
    password: ''
  };

  private static propKey(propertyName: string, value: any): object {
    return { [propertyName]: value };
  }

  public constructor(props: InterfaceProps) {
    super(props);
    this.state = { ...Parent.INITIAL_STATE };
  }

  public render() {
    const { password } = this.state;
    return (
     <Child setStateWithEvent={setStateWithEvent} password={password}/>;
    );
  }
  private setStateWithEvent(event: any, columnType: string): void {
    this.setState(
      Parent.propKey(columnType, (event.target as any).value)
    );
  }
}

而子组件是

const Child = ({
  password,
  setStateWithEvent
}: InterfaceProps) => {

  return (
     <input
         name="password"
         value={password}
         onChange={(event: any) => setStateWithEvent(event, 'password')}
         type="password"
         placeholder="Password"
     />
  );
};

如何使用statesetStateWithEvent从孩子传递给父母?

2 个答案:

答案 0 :(得分:3)

您需要将setStateWithEvent函数绑定到Parent中。

将此添加到您的构造函数中:

this.setStateWithEvent = this.setStateWithEvent.bind(this);

答案 1 :(得分:0)

您可以使用以下箭头功能:

private setStateWithEvent = (event: any, columnType: string) => {
    this.setState(
      Parent.propKey(columnType, (event.target as any).value)
    );
  }

请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions了解更多详细信息。