Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/url/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript TypeError:无法读取属性';设置状态';未定义事件的使用_Javascript_Reactjs_Typescript - Fatal编程技术网

Javascript TypeError:无法读取属性';设置状态';未定义事件的使用

Javascript TypeError:无法读取属性';设置状态';未定义事件的使用,javascript,reactjs,typescript,Javascript,Reactjs,Typescript,我在将值从子组件传递到父组件时遇到一些问题状态。给出的错误是TypeError:在输入中输入值时,无法读取未定义的属性“setState” interface InterfaceState { password: string; } class Parent extends Component<InterfaceState> { private static INITIAL_STATE = { password: '' }; private static

我在将值从子组件传递到父组件时遇到一些问题
状态
。给出的错误是
TypeError:在
输入中输入值时,无法读取未定义的属性“setState”

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)
    );
  }
}
接口接口属性{
密码:字符串;
}
类父级扩展组件{
私有静态初始状态={
密码:“”
};
私有静态propKey(propertyName:string,value:any):对象{
返回{[propertyName]:值};
}
公共构造函数(道具:InterfaceProps){
超级(道具);
this.state={…Parent.INITIAL_state};
}
公共渲染(){
const{password}=this.state;
返回(
;
);
}
私有setStateWithEvent(事件:任意,列类型:字符串):void{
这是我的国家(
Parent.propKey(columnType,(event.target为任意).value)
);
}
}
子组件是

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

  return (
     <input
         name="password"
         value={password}
         onChange={(event: any) => setStateWithEvent(event, 'password')}
         type="password"
         placeholder="Password"
     />
  );
};
const Child=({
密码,
setStateWithEvent
}:InterfaceProps)=>{
返回(
setStateWithEvent(事件“密码”)}
type=“密码”
占位符=“密码”
/>
);
};

如何使用
setStateWithEvent
state
从子级传递到父级?

您需要在
parent
中绑定
setStateWithEvent
函数

将其添加到构造函数中:

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

您可以按如下方式使用箭头功能:

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

有关更多详细信息,请参阅。

在父级构造函数中尝试绑定
setStateWithEvent
this.setStateWithEvent=this.setStateWithEvent.bind(this)