将道具传递给组件儿童

时间:2017-03-17 03:22:34

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

由于无法将我的道具传递给子组件,我遇到了React的问题。我已经阅读了文档,但我仍然对需要采取的步骤感到困惑。这是使用Ruby on Rails和react_on_rails gem完成的。此时,Redux尚未使用,我仍在使用React学习绳索。

我正在使用react_component从rails发送变量,其中包含以下内容:

index.html.erb

<%= react_component('Lifts', props: @lifts, prerender: true) %>

尝试在React中提取它。数据显示在Chrome开发工具的“元素”部分下。但是,我假设我可能没有正确绑定数据。似乎没有任何东西出现在LiftsList.jsx中。也许解决方案显而易见,但它现在真的逃避了我。

Lifts.jsx

import React, { PropTypes } from 'react';
import LiftsList from './LiftsList';
import Lift from './Lift';
export default class Lifts extends React.Component {

  constructor(props, _railsContext) {
    super(props);
    this.state = {
      id: props.id,
      date: props.date,
      liftname: props.liftname,
      weightlifted: props.weightlifted,
      repsformed: props.repsformed,
    }
  }
  render() {
    return (
      <div className="container" style={{display : 'inline-block'}}>
        <ul>
          <LiftsList lifts = {this.state.lifts} />
        </ul>
      </div>
    );
  }
}

LiftsList.jsx

import React, {PropTypes} from 'react';
import Lift from './Lift';
export default class LiftsList extends React.Component {

  render() {
    let lifts = this.state.lifts.map(lift =>
      <Lift key={prop.id} {...lift} />);
    return (
      <div>
        <div>???</div>
      </div>
    );
  }
}

Lift.jsx

import React, {PropTypes} from 'react';
export default class Lift extends React.Component {

  render() {
    return (
      <ul>
        <li>{this.props.id}</li>
        <li>{this.props.date}</li>
        <li>{this.props.liftname}</li>
        <li>{this.props.ismetric}</li>
        <li>{this.props.weightlifted}</li>
        <li>{this.props.repsformed}</li>
      </ul>
    );
  }
}

1 个答案:

答案 0 :(得分:0)

在升降机中,您的state似乎未使用,而不是this.state.lifts我认为您要使用this.state.props

您可能需要以下内容:

  constructor(props, _railsContext) {
    super(props);
  }
  render() {
    return (
      <div className="container" style={{display : 'inline-block'}}>
        <ul>
          <LiftsList lifts={this.props.lifts} />
        </ul>
      </div>
    );
  }

同样地,在LiftsList中,你可能想要这样的东西:

render() {
  let lifts = this.props.lifts.map(lift =>
    <Lift key={lift.id} {...lift} />);
  return (
    <div>
      <div>???</div>
    </div>
  );
}

state取代props并从lift获取您的身份

请参阅:What is the difference between state and props in React?

相关问题