【问题标题】:Passing props to component children将 props 传递给子组件
【发布时间】:2017-03-17 03:22:34
【问题描述】:

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

我使用 react_component 从 rails 发送一个变量,内容如下:

index.html.erb

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

尝试在 React 中获取它。数据显示在 Chrome 开发工具的 Elements 部分下。但是,我假设我可能没有正确绑定数据。 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>
    );
  }
}

【问题讨论】:

  • 在 Lifts.jsx 中为 lifts = {this.state.lifts} 您尚未在该州定义电梯。

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


【解决方案1】:

在 Lifts 中,您的 state 似乎未被使用,我认为您想使用 this.state.props 而不是 this.state.lifts

你可能想要这样的东西:

  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 获取您的ID

见:What is the difference between state and props in React?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-09
    • 2018-08-11
    • 1970-01-01
    相关资源
    最近更新 更多