在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中常用的几种页面之间传值的方法,可以根据具体的需求选择适合的方法。