【发布时间】:2021-10-22 05:49:24
【问题描述】:
我对 React 很陌生,这是我在现有项目中的第一个任务..!好的,言归正传,所以有一个父组件 ContactForm.js,它有子组件 UserInfoStep.js。父组件中有一个按钮,我需要根据子组件中的切换按钮启用/禁用它。我曾尝试使用回调,但它给了我错误..
TypeError: Cannot read properties of undefined (reading 'callbackFunction')
ContactForm.js
const callbackFunction = (isChecked) => {
//do enable/disable
this.Button.disabled = isChecked;
};
function ContactForm() {
const [buttonState, setButtonState] = useState(true);
const { PUID,FirstName, LastName, EurofinsLegalEntity, EurofinsBusinessUnit, StartDate, EndDate, frequency, test, exp, signed, laptop, transfer, existing, newL, categories} = state;
const steps = [
<UserInfoStep parentCallback = {this.callbackFunction} {...{ PUID,FirstName, LastName, EurofinsLegalEntity, EurofinsBusinessUnit, StartDate, EndDate}} />];
return (
<ContactFormContext.Provider value={{ dispatch }}>
//some code removed
<Button
disabled={buttonState}
type="submit"
className={classes.button}
color="primary"
variant="outlined"
onClick={e => {
e.preventDefault();
if (isLast) {
handleSubmit();
} else {
goForward();
}
}}
>
{isLast ? "Submit" : "Next"}
</Button>
//some code removed
</ContactFormContext.Provider>
);
}
export default ContactForm;
UserInfoStep.js
function UserInfoStep ({ PUID, FirstName, LastName, EurofinsLegalEntity, EurofinsBusinessUnit, StartDate, EndDate }) {
const { dispatch } = useContext(ContactFormContext);
const [checked, setChecked] = useState(false);
const handleChange = () => {
setChecked((prev) => !prev);
//as soon as this is checked, enable the button in contactForm
sendData(checked);
};
const sendData = (isChecked) => {
this.parentCallback(isChecked);
//Enabled = isChecked;
};
return(
//some controls
<FormControlLabel
control={<Switch checked={checked} onChange={handleChange} />}
/>
);
}
export default UserInfoStep;
【问题讨论】:
-
我猜您的代码正在从类组件转换为功能组件。在 ContactForm.js 中,您正在使用状态但未定义。请编辑您的问题
标签: javascript reactjs