在React中,可以使用以下幾種方法在頁面之間傳值:
// ParentComponent.js
import React from 'react';
import ChildComponent from './ChildComponent';
const ParentComponent = () => {
const value = 'Hello!';
return (
<ChildComponent value={value} />
);
};
export default ParentComponent;
// ChildComponent.js
import React from 'react';
const ChildComponent = (props) => {
return <div>{props.value}</div>;
};
export default ChildComponent;
// ValueContext.js
import React from 'react';
const ValueContext = React.createContext();
export default ValueContext;
// ParentComponent.js
import React from 'react';
import ValueContext from './ValueContext';
import ChildComponent from './ChildComponent';
const ParentComponent = () => {
const value = 'Hello!';
return (
<ValueContext.Provider value={value}>
<ChildComponent />
</ValueContext.Provider>
);
};
export default ParentComponent;
// ChildComponent.js
import React from 'react';
import ValueContext from './ValueContext';
const ChildComponent = () => {
return (
<ValueContext.Consumer>
{value => <div>{value}</div>}
</ValueContext.Consumer>
);
};
export default ChildComponent;
// App.js
import React from 'react';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import ParentComponent from './ParentComponent';
import ChildComponent from './ChildComponent';
const App = () => {
return (
<Router>
<Route path="/" exact component={ParentComponent} />
<Route path="/child/:value" component={ChildComponent} />
</Router>
);
};
export default App;
// ParentComponent.js
import React from 'react';
import { Link } from 'react-router-dom';
const ParentComponent = () => {
const value = 'Hello!';
return (
<div>
<Link to={`/child/${value}`}>Go to Child Component</Link>
</div>
);
};
export default ParentComponent;
// ChildComponent.js
import React from 'react';
const ChildComponent = (props) => {
const value = props.match.params.value;
return <div>{value}</div>;
};
export default ChildComponent;
以上是React中常用的幾種頁面之間傳值的方法,可以根據具體的需求選擇適合的方法。