找到问题的解决方案后,我遇到了另一个问题。在我的路线上添加路线参数后,反应路由器不再识别它。
组件渲染新路径
import React, { Component } from 'react'
import { hashHistory } from 'react-router'
class Name extends Component {
constructor() {
super();
this.state = {username: ''};
this.onClickFunction = this.onClickFunction.bind(this)
}
onClickFunction(e) {
this.setState({username: e.target.value})
hashHistory.push({
pathname: '/level/' + this.state.username
})
}
render() {
return (
<div className="row">
<div className="col-md-12">
<div className="nameBox">
<form className="form-inline">
<input type="text" className="form-control" placeholder="Desiered Username" onChange={this.onUpdateUser} />
<button type="submit" className="btn btn-success" onClick={ this.onClickFunction }>Submit</button>
</form>
</div>
</div>
</div>
)
}
}
export default Name
import React from 'react'
import { Router, Route, hashHistory } from 'react-router'
import Home from './Home.js'
import Name from './Name.js'
import Level from './level.js'
import Level1 from './level1.js'
import Level2 from './level2.js'
//import result from './result.js'
const routes = (
<Router history={hashHistory}>
<Route path='/' component={Home} >
<Route path='/name' component={Name} />
<Route path="/level/:username" component={Level} />
<Route path='/level1' component={Level1} />
<Route path='/level2' component={Level2} />
</Route>
</Router>
);
export default routes;
我是React的新手,这是我第一个帮助他学习它的应用。我已经谷歌搜索了,虽然普遍存在,但这个问题似乎含糊不清。非常感谢任何帮助!谢谢!
答案 0 :(得分:2)
利用this.context.router.push()
发送动态路由以及event e
没有引用输入但是按钮,e.target.value
不会给出值输入。您应该实现onUpdateUser
函数以使用输入值
import React, { Component } from 'react'
import { hashHistory } from 'react-router'
class Name extends Component {
constructor() {
super();
this.state = {username: ''};
this.onClickFunction = this.onClickFunction.bind(this);
this.onUpdateUser = this.onUpdateUser.bind(this);
}
static contextTypes = {
router: React.PropTypes.object
}
onClickFunction() {
this.context.router.push({
pathname: '/level/' + this.state.username
})
}
onUpdateUser(e) {
this.setState({username: e.target.value});
}
render() {
return (
<div className="row">
<div className="col-md-12">
<div className="nameBox">
<form className="form-inline">
<input type="text" className="form-control" placeholder="Desiered Username" onChange={this.onUpdateUser.bind(this)} />
<button type="button" className="btn btn-success" onClick={ this.onClickFunction.bind(this) }>Submit</button>
</form>
</div>
</div>
</div>
)
}
}
export default Name