嗨,我是 React 新手,用一种表单编写了一个小应用程序来进行一些练习。除了 App.js
文件之外,它由 4 个组件组成。我试图让我的 Checkbox.js
组件与我的 SubmitButton.js
组件进行通信,无论它是否被选中,以便只有在用户选中时才会启用提交按钮盒子。我尝试使用 props,正如您在下面的代码中看到的那样,但我可能这样做是非常错误的。谁能帮助我学习正确的方法来做到这一点?不确定这是否重要,但我正在使用 Material-UI 库。谢谢。
App.js
import React from 'react';
import NavBar from './Components/NavBar'
import Form from './Components/InfoForm'
import SubmitButton from './Components/SubmitButton';
import Container from '@material-ui/core/Container';
import Checkbox from './Components/Checkbox';
import './App.css';
function App() {
const [state, setState] = React.useState({
checked: false,
});
const handleChange = name => event => {
setState({ ...state, [name]: event.target.checked });
};
return (
<div>
<Container maxWidth="md">
<NavBar />
<Form />
<br />
<Checkbox onChange={handleChange('checked')} checked={state.checked} />
<SubmitButton isEnabled={state.checked} />
</Container>
</div>
);
}
export default App;
Checkbox.js
import React from 'react';
import Checkbox from '@material-ui/core/Checkbox';
function Checkboxes() {
return (
<div>
<Checkbox
name = 'checkbox'
value="checked"
inputProps={{ 'aria-label': 'primary checkbox', }}
/> By checking this box you agree to all terms and conditions specified above.
</div>
);
}
export default Checkboxes;
SubmitButton.js
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';
const useStyles = makeStyles(theme => ({
button: { margin: theme.spacing(1), },
input: { display: 'none', },
}));
export default function ContainedButtons(props) {
const classes = useStyles();
if (props.isEnabled === 'true') {
return (
<div>
<Button variant="contained" color="primary" className={classes.button}>
Submit
</Button>
</div>
);
} else
{
return (
<div>
<Button variant="contained" color="primary" className={classes.button} disabled = 'true'>
Submit
</Button>
</div>
);
}
}
最佳答案
最基本、最直接的方法是将共享功能提升到父组件中,并将值和函数作为 props 传递给子组件。
在您的情况下,在App
中有一些状态来维护复选框是否被选中,然后通过 Prop 将值和更新函数传递到复选框。然后,您也可以根据 App
状态下复选框指示器的值来切换 App
中的按钮
换句话说,您在全局窗口对象上使用指标的想法是正确的,但是,请使用父组件而不是全局变量。当您发现需要真正使事物变得“全局”或可以从应用程序的各个部分进行访问时,请考虑使用 Redux 等进行状态管理
例如
function App() {
const [state, setState] = React.useState({
checked: false,
});
return (
<div>
<Container maxWidth="md">
<NavBar />
<Form />
<br />
<Checkbox onChange={handleChange('checked')} checked={checked}/>
<SubmitButton isEnabled={checked}/>
</Container>
</div>
);
}
关于javascript - react : Communicate between sibling components,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56545832/