我在将值从子组件传递到父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"
/>
);
};
如何使用state
将setStateWithEvent
从孩子传递给父母?
答案 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了解更多详细信息。