我想首先获取用户输入,将用户输入存储到this.state.value中,并在用户单击1时使用标签将this.state.value从首页传递到示例页面。
现在,我编写的源代码(如下所示)获取用户的输入,并将输入存储到this.state.value中,但是无法将this.state.value从首页传递到示例页面。
单击1按钮时,我什么都看不到。我该如何解决?
app.js
import React from "react";
import "./App.css";
import {
BrowserRouter as Router,
Route,
Switch,
Link,
Redirect
} from "react-router-dom";
import Home from "./pages/home";
import Sample from "./pages/sample1";
function App() {
return (
<Router>
<Switch>
<Route exact path="/home" component={Home} />
<Route exact path="/sample1" component={Sample} />
<Redirect to="/404" />
</Switch>
</Router>
);
}
Home.jsx
import React, { Component } from "react";
import { Link } from "react-router-dom";
class Home extends Component {
constructor(props) {
super(props);
this.state = { value: "" };
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({ value: event.target.value });
}
handleSubmit(event) {
alert("A name was submitted: " + this.state.value);
event.preventDefault();
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input
type="text"
value={this.state.value}
onChange={this.handleChange}
/>
</label>
<input type="submit" value="Submit" />
</form>
<a class="page-link">
<Link
to={{
pathname: "/sample1",
state: this.state.value
}}
>
1
</Link>
</a>
</div>
);
}
}
export default Home;
Sample.jsx
import React, { Component } from "react";
class Sample extends Component {
render() {
return <div>{this.props.location.state}</div>;
}
}
export default Sample;