如何将函数组件AddFile.js中的useState变量selectedFile传递给兄弟文件index.js?
The error you're seeing makes total sense—selectedFile is a local state variable inside your AddFile component, not a top-level export. You can't directly export a component's internal state like a regular function or variable because it's tied to the component's lifecycle and unique instance.
The simplest and most idiomatic way to share state between sibling components (like AddFile.js and index.js) is to lift the state up to their closest common parent component. Here's how to do it step by step:
Step 1: Move the State to the Common Parent
First, identify or create a parent component that renders both AddFile and your sibling component from index.js. Let's assume this parent is App.js. We'll move the useState hook here to manage the shared state.
// App.js import { useState } from 'react'; import { AddFile } from './AddFile'; import { YourSiblingComponent } from './index'; // Replace with your actual component name from index.js function App() { // This state will be shared between both siblings const [selectedFile, setSelectedFile] = useState(''); return ( <div className="parent-container"> {/* Pass the setter function to AddFile so it can update the state */} <AddFile setSelectedFile={setSelectedFile} /> {/* Pass the current selectedFile value to your sibling component */} <YourSiblingComponent selectedFile={selectedFile} /> </div> ); } export default App;
Step 2: Update AddFile.js to Use the Parent's Setter
Modify AddFile.js to accept the setSelectedFile function as a prop instead of declaring its own state. This way, any changes to the input will update the parent's state, which is then available to the sibling.
// AddFile.js export function AddFile({ setSelectedFile }) { return ( <div className="App"> <label> Add your own template!</label> {/* We no longer need a local value prop since state is controlled by the parent */} <input type="file" name="file_name" onChange={(e) => setSelectedFile(e.target.value)} /> </div> ); };
Step 3: Access the State in Your Sibling Component (index.js)
In index.js, accept selectedFile as a prop and use it wherever you need it.
// index.js export function YourSiblingComponent({ selectedFile }) { // Use the selectedFile value here return ( <div> <p>Selected file path: {selectedFile}</p> {/* Add your component logic here */} </div> ); }
Why This Works
Lifting state up is a core React pattern. By moving the shared state to a common parent, you ensure both sibling components have access to the same source of truth. The parent manages the state, while the children receive either the state value (to display) or the setter function (to update it) as props.
For more complex apps with many components needing access to the same state, you could use React's Context API or a state management library like Redux, but for sibling components, lifting state up is the cleanest and most straightforward solution.
内容的提问来源于stack exchange,提问作者shidog12345

