【问题标题】:ReactJS: Pass parameter from rails to react router to componentReactJS:从 rails 传递参数以将路由器反应到组件
【发布时间】:2018-04-28 00:14:01
【问题描述】:

我正在尝试将一个值从渲染函数传递给组件:

= react_component('App', props: {test: 'abc'}, prerender: false)

Routes.jsx

<Route path="/" component={App} >

App.jsx(组件)

class App extends React.Component {
  render() {
    return (
      <Header test={this.props.test}>
      </Header>
      {this.props.children}
      <Footer />
    );
  }
}

App.propTypes = { test: PropTypes.string };

对于这个完整的流程似乎没有一个连贯的答案。

我尝试了以下方法:

<Route path="/" component={() => (<App myProp="value" />)}/>

但这仍然没有回答获取初始渲染调用(react_component)提供的值的问题

【问题讨论】:

  • 改用render
  • 你使用的是哪个版本的 React Router?
  • @Dez 我正在使用 react-router 3.0.5
  • @SterlingArcher 您能否使用渲染提供端到端的答案?这将有很大帮助
  • @AlexJose 当然,这是我如何将它与道具一起使用的示例github.com/RUJodan/Source-React/blob/master/src/index.jsx

标签: javascript reactjs react-router react-on-rails


【解决方案1】:

寻找关于如何从 “视图”到“反应路由器”到“组件”

我们将从视图开始:

<%= react_component('MyRoute', {test: 123}, prerender: false) %>

现在我们将创建一个包含 route 的组件:

class MyRoute extends Component{
  constructor(props){
    super(props)
  }
  render(){
    return(
      <Switch>
        <Route path="/" render={() => <App test={this.props.test} />} />
        <Route path="/login" component={Login} />
      </Switch>
    )
  }
}

如您所见,我们将test 属性从Route 组件传递给App 组件。现在我们可以在App 组件中使用test 属性:

class App extends Component{
  constructor(props){
    super(props)
  }
  render(){
    return(
      <h1>{this.props.test}</h1>
    )
  }
}

【讨论】:

  • 这似乎在第一步本身引发错误,同时从视图中调用组件。 ArgumentError(wrong number of arguments (given 3, expected 1..2)
  • 尝试删除prerender: false
【解决方案2】:
<Route path="/" render={attr => <App {...attr} test="abc" />} />

【讨论】:

    【解决方案3】:

    在路由器 v3 中你会做这样的事情

    像这样将你的 App 组件包裹在 withRouter 下

    import { withRouter } from 'react-router';
    
    class App extends React.Component {
      render() {
        return (
          <Header test={this.props.test}>
          </Header>
          {
            this.props.children &&
            React.clone(this.props.children, {...this.props} )}
          <Footer />
        );
      }
    }
    App.propTypes = { test: PropTypes.string };
    export const APP = withRouter(App);
    

    然后像这样构建你的路线......

    <Route path="/" component={APP}>
      <Route path="/lobby" component={Lobby} />
      <Route path="/map" component={GameMap} />
      ...
    </Route>
    

    因此,您的子路由将在 APP 子属性中呈现,并且道具将被传递给它们。

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 2016-06-02
      • 2019-08-15
      • 1970-01-01
      • 1970-01-01
      • 2016-05-26
      • 1970-01-01
      • 2020-11-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多