[英]React Component calling method to a different component
我有一个具有以下结构的页面
const Upload = (props) => {
return (
<BaseLayout>
<ToolbarSelection />
<Box>
<FileDropArea />
</Box>
</BaseLayout>
)
}
我有一个在组件<FileDropArea />
中工作的方法
这是用作示例的方法
const allSelection = () => {
setFiles((files) =>
files.map((file) => {
file.checked = true;
return file;
})
);
};
在 React 中,我如何从<ToolbarSelection />
组件中调用此方法allSelection
,其中我有我的简单按钮,例如<Button>All Selection</Button>
你需要像这样使用React Context
:
//create a fileContext.js
const fileContext = React.createContext();
const useFileContext = () => React.useContext(fileContext);
const FileContextProvider = ({ children }) => {
const [files, setFiles] = useState([]);
const allSelection = () => {
setFiles((files) =>
files.map((file) => {
file.checked = true;
return file;
})
);
};
// if you have other methods which may change the files add them here
return (
<fileContext.Provider
value={{
files,
setFiles,
allSelection,
}}
>
{children}
</fileContext.Provider>
);
};
在上传文件中使用 fileContextProvider
const Upload = (props) => {
return (
<FileContextProvider>
<BaseLayout>
<ToolbarSelection />
<Box>
<FileDropArea />
</Box>
</BaseLayout>
</FileContextProvider>
);
};
使用它,例如在 ToolbarSelection 中,如下所示:
const ToolbarSelection = () => {
const {files, allSelection} = useFileContext();
// do other stuff
}
我假设您希望使allSelection
function 可重复使用。 Hooks是一种让逻辑在组件间可重用的好方法。
创建一个自定义钩子useAllSelection
。 请注意,钩子应该有一个use前缀。
const useAllSelection = (files) => {
const [files, setFiles] = useState([]);
const handleAllSelection = () => {
setFiles((files) =>
files.map((file) => {
file.checked = true;
return file;
})
);
};
return { handleAllSelection };
};
const ToolbarSelection = () => {
// import the hook and use
const { handleAllSelection } = useAllSelection();
return (
<button onClick={handleAllSelection}>All Selection</button>
)
}
ReactJS 允许以不同的方式执行此方案。 让我解释一下:如果您按下 ToolbarSelection 中的按钮,则将该按钮的新 state 的值作为道具传递给 FileDropArea。 然后,在 FileDropArea 渲染中,根据该属性的值调用或不调用该方法
const Upload = (props) => {
return (
<BaseLayout>
<ToolbarSelection
onSelectionClick={(value) => setSelected(value)}
/>
<Box>
<FileDropArea
selected = { /* state of a button in the Toolbar */}
/>
</Box>
</BaseLayout>
)
}
请注意工具栏中的回调如何更改 state,以及如何将这个新的 state 作为属性传递给 FileDropArea
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.