我正在设计一个简单的网页,其中包含将用户带到新加载的页面的按钮。我不确定如何在新页面上显示组件。对于所有组件,我都有单独的.js文件(例如:RideForm.js拥有在屏幕上呈现功能下拉菜单的代码)因此,例如,如果我想单击“计划行程”按钮并设置一个新页面加载了下拉菜单,该如何将其添加到代码中?
//PlanButton.js
import React from 'react'
import { Redirect } from 'react-router-dom'
import DropDownMenu from "./DropDownMenu"
class PlanButton extends React.Component {
state = {
redirect: false
}
setRedirect = () => {
this.setState({
redirect: true
})
}
renderRedirect = () => {
if (this.state.redirect) {
return <Redirect to='/plan' />
}
}
render () {
return (
<div>
{this.renderRedirect()}
<button onClick={this.setRedirect}>Plan Your Trip</button>
</div>
)
}
}
export default PlanButton
---------------------------Separate File-----------------------------
//RideForm.js
import React from "react"
class RideForm extends React.Component {
constructor(props) {
super(props);
//beginning option (can be anything)
this.state = {value: 'Space Mountain'};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
//simply a pop up window to check the result
handleSubmit(event) {
alert('Your ride is: ' + this.state.value);
event.preventDefault();
}
//set up of the drop down
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Pick your ride:
<select value={this.state.value} onChange={this.handleChange}>
<option value="Pirates">Pirates</option>
<option value="Autopia">Autopia</option>
<option value="Haunted Mansion">Haunted Mansion</option>
<option value="Space Mountain">Space Mountain</option>
<option value="Splash Mountain">Splash Mountain</option>
</select>
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
export default RideForm
答案 0 :(得分:0)
如果我的理解正确,您可以按照react-router's documentation给出的示例进行操作。
您需要使用几个组件:
Router
,将react-router
插入浏览器的历史记录
Link
,将用户引导到另一条路线。链接可能比按钮更好。您可以将链接样式设置为按钮
Route
,以根据路线定义要渲染的组件