在 React 中传递组件之间依赖关系的正确方法是什么?

What's the proper way to pass dependencies between components in React?

假设组件 A 创建了组件 B 需要显示的项目列表。从 parent 将数据从组件 A 传递到组件 B 的正确方法是什么?

例如,假设组件 A 的构造函数创建了一个项目列表,并且有一个函数 _getListItems() returns 该列表。我希望 parent 可以通过 props 将该列表传递给其他组件。

我的天真 (non-working) 实现 parent 试图渲染这样的组件:

render () {
    return (
      <div>
        <h1>Data Test</h1>        
        <ComponentA ref='compa'/>
        <ComponentB items={this.refs.compa._getListItems()}/>
      </div>
    );
}

...虽然上面的代码不起作用,但我希望它能说明我正在尝试做的事情。

ps。 nOOb 做出反应 javascript,如果我的问题的答案很明显,请原谅我...

将您的组件分为两个不同的类别。

  • 负责显示事物的展示组件。该组件不应有状态(UI 状态除外)。
  • 知道数据的容器组件。

https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0#.skmxo7vt4

因此,在您的情况下,数据应由 ComponentAComponentB 的父级创建,并通过 props 将数据传递给 ComponentAComponentB

示例:

render(){
    let items = this._getListItems();
    return (
        <div>
            <ComponentA items={items} />
            <ComponentB items={items} />
        </div>
    );
}

编辑

在评论中重写OP的方法:

class MyContainer extends React.Component { 
    constructor(props) { 
        super(props);
        this.state = { stuff: [1,2,3] }; 
    } 

    render() { 
        return ( 
            <div>
                <ComponentA items={this.state.stuff} /> 
                <ComponentB items={this.state.stuff} /> 
            </div> 
        ); 
    } 
}

根据上面接受的答案,我刚刚有一个(相关的)EUREKA 时刻,所以我将扩展答案;当父级使用自己的状态将道具传递给其子级时,只要父级的状态发生变化,就会调用其 render() 函数,从而使用更新后的状态更新子级。所以你可以这样做:

class MyContainer extends React.Component { 
    constructor(props) { 
        super(props);

        let sltd = this.props.selected
        this.state = { 
          stuff: [1,2,3], 
          selected: sltd
        }; 
    } 

    _handleAStuff(value) {
        this.setState(selected: value)
        //do other stuff with selected...
    }

    _handleBStuff(value) {
        this.setState(selected: value)
        //do other stuff with selected...
    }

    render() { 
        return ( 
            <div>
                <ComponentA items={this.state.stuff} selected={this.state.selected} parentFunc={this._handleAStuff.bind(this)} /> 
                <ComponentB items={this.state.stuff} selected={this.state.selected} parentFunc={this._handleBStuff.bind(this)} /> 
            </div> 
        ); 
    } 
}

MyContainer.defaultProps = {
  selected: 0
}

class ComponentA extends React.Component {

  constructor(props) {
    super(props)
  }

  _handleSelect(value) {
    this.props.parentFunc(value.label)
  }

render() {

    const itm = this.props.items.map(function(values) {
      return { value: values, label: values}
    })

    return (
      <div>
        <Select
          options={itm}
          value={this.props.selected}
          onChange={this._handleSelect.bind(this)}
        />
      </div>
    );
  }
}

// ComponentB...

上面的回调模式意味着ComponentA和ComponentB不需要维护状态,它们只是'render stuff',这也很酷。我开始看到 REACT 的力量...