将子数据传递给父?

Pass child data to parent?

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

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

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

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

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

您可以改为将状态保留在父级中,并将一个函数作为 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>

在 React 中,数据流是单向的,即从父级到子级。 如果父组件想要访问子组件数据,可以使用 refs(虽然不推荐)。

例如: 假设您在子组件中定义了一个函数 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
  };   
}

希望对您有所帮助。