[英]How to get a state from a different component in React
我需要根据取自不同组件的值禁用reactjs
中的按钮。
在下面的组件( main.js
)中,我需要禁用按钮。 但这必须根据取自另一个组件( upload.js
)的值的值来禁用
export default function HorizontalLabelPositionBelowStepper() {
.
.
.
return (
<Grid container>
<Grid item lg="12" md="12" xs="12">
<div className={classes.root}>
<div>
<Grid container justify="center">
<Grid item md="1">
<Button // button I need to disable
variant="contained"
color="secondary"
onClick={handleNext}
endIcon={<NavigateNext />}
>
{activeStep === steps.length - 1 ? "Finish" : "Next"}
</Button>
</Grid>
</Grid>
</div>
</div>
</Grid>
</Grid>
);
}
这是upload.js
// imports...
.
.
.
export default function ElevateAppBar(props) {
const [file, setFile] = useState('');
const [filename, setFileName] = useState('eg: employees.csv'); // this filename value should be passed to the component `main.js`
return (
<Grid container justify="flex-start">
<Grid container item lg="12" md="12">
<Grid item lg="4" md="4" xs="4">
<Form>
<Form.File id="custom-file" label={filename} custom />
</Form>
</Grid>
</Grid>
<Grid container justify="center">
<Button variant="contained" style={{backgroundColor: "lightgreen"}} endIcon={<CloudUpload />}>
Upload
</Button>
</Grid>
</Grid>
);
}
在upload.js
,我有一个名为filename
的变量。 我需要将此值传递给第一个组件 - 即main.js
所以逻辑可能是这样的(这不是 reactjs 语法,这只是为了说明我需要做什么):
if(filename_taken_from_upload_js == "eg: employees.csv"){
// disable the button
}else{
// enable the button
}
有人可以帮忙吗?
这可能是提升 state 的情况:https://reactjs.org/docs/lifting-state-up.html#lifting-state-up
如果这个值可以被其他不相关的组件使用,你应该考虑把它放在一个全局 state 中,使用 Redux 或上下文 API。
https://redux.js.org/faq/react-redux#react-redux https://reactjs.org/docs/context.html#when-to-use-context
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.