将孩子的数据传递给父母?

时间:2018-08-10 15:47:14

标签: reactjs react-props

我想将数据从子组件传递到父组件。

这是我的代码:https://codesandbox.io/s/018488478p

在我的子组件中,我想显示此const = priceShown在父组件中。因此:

<h2>Price:{priceShown}</h2>

我尝试过将函数放在父级中,然后将它们作为道具传递给孩子,这样我就可以访问const = priceShown,因为它将存在于父级中,但是i却未定义。这是该代码:https://codesandbox.io/s/14vyy31nlj

2 个答案:

答案 0 :(得分:1)

您可以改为将状态保留在父级中,并传递一个作为prop的函数,该函数将从子组件中调用,并带有适当的参数,以更新父级中的该状态。

示例

class App extends React.Component {
  state = {
    evenSelected: null
  };

  handleSelectL1 = i => {
    this.setState({
      evenSelected: i,
      oldSelected: null
    });
  };

  render() {
    const product = [
      {
        name: "one",
        price: 1
      },
      {
        name: "two",
        price: 2
      },
      ,
      {
        name: "three",
        price: 3
      }
    ];

    const evenIndex = this.state.evenSelected;

    return (
      <div>
        <Child
          product={product}
          handleSelectL1={this.handleSelectL1}
          evenIndex={evenIndex}
        />
        <h2>Price: </h2>
      </div>
    );
  }
}

class Child extends React.Component {
  render() {
    const { product, evenIndex } = this.props;

    const priceShown = product[evenIndex] && product[evenIndex].price;

    return (
      <div>
        {product.map((p, i) => {
          return (
            <div
              key={p.id}
              className={evenIndex === i ? "selectedRBox" : "selectorRBox"}
              onClick={() => this.props.handleSelectL1(i)}
            >
              <h1 className="selectorTextL">
                {p.name} {evenIndex === i && "selected!"}
              </h1>
            </div>
          );
        })}
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="root"></div>

答案 1 :(得分:1)

在react中,数据流是单向的,即从父级到子级。 如果父组件要访问子组件数据,则可以使用引用(尽管不建议这样做)。

例如: 假设您在子组件中定义了一个函数getPrice()。

class Parent extends React.Component {
constructor(props) {
super(props);
this.getPrice = this.getPrice.bind(this);
};

getPrice() {
    let price = this.refs.child.getPrice();
};

render() {
    return(
        <Child
          ref="child"
        />
    )
  };
}

在子组件中,

class Child extends React.Component {
    constructor(props) {
    super(props);
    this.state = {
        price: "100"
    }
this.getPrice = this.getPrice.bind(this);
};

getPrice() {
    return this.state.price
  };   
}

希望这会有所帮助。

相关问题