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)代码>