美文网首页Web前端之路让前端飞
react 父组件与子组件之间的值传递

react 父组件与子组件之间的值传递

作者: 你期待的花开 | 来源:发表于2017-09-14 11:29 被阅读1368次

    概念上,组件是封闭的环境。React中是单向数据流的设计,也就是是说只有父组件传递资料给子组件这回事。以正确的技术说明,拥有者组件可以设置被拥有者组件中的数据。

    那么子组件要如何与父组件沟通这件事,简单的来说,是一种迂回的作法,在父组件中设置了一个方法(函数),然后传递给子组件的props,子组件在事件触发时,直接呼叫这个props所设置的方法(函数)。但这中间,有谁(对象)呼叫了函数的设置,也就是this的作用。

    父组件到子组件用props设置,子组件到父组件用上面说的方式,这是基本的套路,但它只适用于简单的组件结构,因为它相当麻烦,而且不灵活。那么如果要作到子组件与子组件要彼此沟通这件事,就不是太容易。当然,我想你已经听过,复杂的应用需要额外使用flux或redux来解决这问题,这是必经之路。

    不过,在思考整体的React应用设计时,要有应用领域状态,也就是全局状态的概念。第一是应用领域state(状态)的,通常会在父组件中,而不是子组件中,子组件有可能很多,位于树状结构很深的地方。

    例子:

    子组件

    import React, { Component } from 'react'
    
    export default class Item extends Component {
      constructor(props) {
        super(props)
    
        this.state = {
          prices: 0
        }
      }
    
      handleChange(){
        const prices =800;
        this.setState({
          prices: price
        })
        //用传过来的changePrice属性(props),是个函数,呼叫它把price交给父组件中的函数去处理
        this.props.changePrice(price)
      }
    
      render() {
        const { prices } = this.state;
            return (
              <div>
                  <div onChange={this.handleChange.bind(this)}>
                  </div>
                 <p>{prices}</p>
              </div>
            )
      }
    }
    
    

    父组件

    
    import React, { Component } from 'react';
    import Item from './Item'
    
    class App extends Component {
      constructor(props) {
        super(props)
    
        this.state = {price: 0}
      }
      
      //给子组件用来传price用的方法
      changePrice(price){
        this.setState({price: price})
      }
    
      render() {
        return (
          <div>
            <Item changePrice={this.changePrice.bind(this)}/>
            <p>{this.state.price}</p>
          </div>
        );
      }
    }
    
    export default App;
    

    相关文章

      网友评论

        本文标题:react 父组件与子组件之间的值传递

        本文链接:https://www.haomeiwen.com/subject/lgzrsxtx.html