reactJs的Lifting State Up

Lifting State Up是什么意思? 意思就是可以把子类的state向上传递给它的父类

看下面代码,是从react官方摘抄的

class ProductCategoryRow extends React.Component {
  render() {
    const category = this.props.category;
    return (
      <tr>
        <th colSpan="2">
          {category}
        </th>
      </tr>
    );
  }
}

class ProductRow extends React.Component {
  render() {
    const product = this.props.product;
    const name = product.stocked ?
      product.name :
      <span style={{color: 'red'}}>
        {product.name}
      </span>;

    return (
      <tr>
        <td>{name}</td>
        <td>{product.price}</td>
      </tr>
    );
  }
}

class ProductTable extends React.Component {
  render() {
    const filterText = this.props.filterText;
    const inStockOnly = this.props.inStockOnly;

    const rows = [];
    let lastCategory = null;

    this.props.products.forEach((product) => {
      if (product.name.indexOf(filterText) === -1) {
        return;
      }
      if (inStockOnly && !product.stocked) {
        return;
      }
      if (product.category !== lastCategory) {
        rows.push(
          <ProductCategoryRow
            category={product.category}
            key={product.category} />
        );
      }
      rows.push(
        <ProductRow
          product={product}
          key={product.name}
        />
      );
      lastCategory = product.category;
    });

    return (
      <table>
        <thead>
          <tr>
            <th>Name</th>
            <th>Price</th>
          </tr>
        </thead>
        <tbody>{rows}</tbody>
      </table>
    );
  }
}

class SearchBar extends React.Component {
  constructor(props) {
    super(props);
    this.handleFilterTextChange = this.handleFilterTextChange.bind(this);
    this.handleInStockChange = this.handleInStockChange.bind(this);
  }

  handleFilterTextChange(e) {
    this.props.onFilterTextChange(e.target.value);
  }

  handleInStockChange(e) {
    this.props.onInStockChange(e.target.checked);
  }

  render() {
    return (
      <form>
        <input
          type="text"
          placeholder="Search..."
          value={this.props.filterText}
          onChange={this.handleFilterTextChange}
        />
        <p>
          <input
            type="checkbox"
            checked={this.props.inStockOnly}
            onChange={this.handleInStockChange}
          />
          {' '}
          Only show products in stock
        </p>
      </form>
    );
  }
}

class FilterableProductTable extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      filterText: '',
      inStockOnly: false
    };

    this.handleFilterTextChange = this.handleFilterTextChange.bind(this);
    this.handleInStockChange = this.handleInStockChange.bind(this);
  }

  handleFilterTextChange(filterText) {
    this.setState({
      filterText: filterText
    });
  }

  handleInStockChange(inStockOnly) {
    this.setState({
      inStockOnly: inStockOnly
    })
  }

  render() {
    return (
      <div>
        <SearchBar
          filterText={this.state.filterText}
          inStockOnly={this.state.inStockOnly}
          onFilterTextChange={this.handleFilterTextChange}
          onInStockChange={this.handleInStockChange}
        />
        <ProductTable
          products={this.props.products}
          filterText={this.state.filterText}
          inStockOnly={this.state.inStockOnly}
        />
      </div>
    );
  }
}


const PRODUCTS = [
  {category: 'Sporting Goods', price: '$49.99', stocked: true, name: 'Football'},
  {category: 'Sporting Goods', price: '$9.99', stocked: true, name: 'Baseball'},
  {category: 'Sporting Goods', price: '$29.99', stocked: false, name: 'Basketball'},
  {category: 'Electronics', price: '$99.99', stocked: true, name: 'iPod Touch'},
  {category: 'Electronics', price: '$399.99', stocked: false, name: 'iPhone 5'},
  {category: 'Electronics', price: '$199.99', stocked: true, name: 'Nexus 7'}
];

ReactDOM.render(
  <FilterableProductTable products={PRODUCTS} />,
  document.getElementById('container')
);

这段代码要实现以下效果:
这里写图片描述

当在输入框输入一些文字的时候,能够根据输入的文字搜索结果,然后把过滤的结果显示出来,注意没输入一个字都要过滤检查一次。

现在主要看每次输入一个字符,就过滤一次结果怎么实现的?
首先关注FilterableProductTable 类中有如下代码:

<div>
        <SearchBar
          filterText={this.state.filterText}
          inStockOnly={this.state.inStockOnly}
          onFilterTextChange={this.handleFilterTextChange}
          onInStockChange={this.handleInStockChange}
        />
        <ProductTable
          products={this.props.products}
          filterText={this.state.filterText}
          inStockOnly={this.state.inStockOnly}
        />
      </div>
handleFilterTextChange(filterText) {
    this.setState({
      filterText: filterText
    });
  }

  handleInStockChange(inStockOnly) {
    this.setState({
      inStockOnly: inStockOnly
    })

首先是当SearchBar中输入的文字变化后会调用handleFilterTextChange/handleInStockChange方法,然后把输入的文字作为参数传递进去,然后在handleFilterTextChange/handleInStockChange的方法中调用this.setState更新属性,从而引发渲染操作,并且把新的state传递给ProductTable,ProductTable根据新的属性过滤商品列表,从而把过滤的结果显示出来。

这个是整体的流程。
需要有两个地方注意:
1.

handleFilterTextChange/handleInStockChange是SearchBar的属性,应该属于SearchBar的方法,而且也是被SearchBar触发调用的,但最终实现是在FilterableProductTable
中,而且在方法中用到了this关键字,那么方法中的this指的应该是SearchBar,怎么才能让this指向FilterableProductTable
? 答案就是:

this.handleFilterTextChange = this.handleFilterTextChange.bind(this);
    this.handleInStockChange = this.handleInStockChange.bind(this);

2.
onFilterTextChange函数是怎么被触发的?
首先看SearchBar:

handleFilterTextChange(e) {
    this.props.onFilterTextChange(e.target.value);
  }

  handleInStockChange(e) {
    this.props.onInStockChange(e.target.checked);
  }

  render() {
    return (
      <form>
        <input
          type="text"
          placeholder="Search..."
          value={this.props.filterText}
          onChange={this.handleFilterTextChange}
        />
        <p>
          <input
            type="checkbox"
            checked={this.props.inStockOnly}
            onChange={this.handleInStockChange}
          />
          {' '}
          Only show products in stock
        </p>
      </form>
    );

input标签有个onChange属性,当输入的文字变化的时候会触发该方法,然后该方法用调用了handleFilterTextChange
-> this.props.onFilterTextChange(e.target.value),最终调用了它属性里面的onFilterTextChange方法,这个方法是在FilterableProductTable中指定并定义的,所以就调用到了FilterableProductTable中的onFilterTextChange方法,其实就是通过props实现了一个回调函数。

这样最终就实现了,状态的向上传递。

1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看REAdMe.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看REAdMe.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看READme.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。
1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 、 1资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看READmE.文件(md如有),本项目仅用作交流学习参考,请切勿用于商业用途。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。
好的,以下是一个使用 React 上下文(Context)共享变量的案例: 假设我们有一个组件 `A`,以及它的两个子组件 `B` 和 `C`,它们都需要使用一个共同的变量 `theme`,我们可以使用 React 上下文(Context)机制来将 `theme` 存储在上下文中,并在需要使用该变量的子组件中通过 useContext 钩子来获取该变量。 ```jsx import React, { createContext, useContext, useState } from "react"; const ThemeContext = createContext("light"); function A(props) { return ( <div> <p>子组件 B 中的 theme 值为:{useContext(ThemeContext)}</p> <p>子组件 C 中的 theme 值为:{useContext(ThemeContext)}</p> </div> ); } function B(props) { return ( <div> <p>子组件 B 中的 theme 值为:{useContext(ThemeContext)}</p> </div> ); } function C(props) { return ( <div> <p>子组件 C 中的 theme 值为:{useContext(ThemeContext)}</p> </div> ); } function App() { const [theme, setTheme] = useState("light"); return ( <ThemeContext.Provider value={theme}> <p>父组件中的 theme 值为:{theme}</p> <button onClick={() => setTheme(theme === "light" ? "dark" : "light")}> 切换主题 </button> <A /> </ThemeContext.Provider> ); } export default App; ``` 在上面的代码中,我们首先使用 `createContext` 函数创建了一个名为 `ThemeContext` 的上下文对象,并将其初始值设为 `"light"`。然后,在组件 `A` 中通过 `useContext` 钩子来获取 `ThemeContext` 上下文中的值,并将其显示出来。同样的,子组件 `B` 和 `C` 中也使用了相同的方式来访问 `ThemeContext` 中的值。 在父组件 `App` 中,我们将 `theme` 变量存储在 `ThemeContext` 的 `Provider` 中,并通过 `value` 属性将其传递给子组件。当我们点击父组件中的切换主题按钮时,`theme` 变量的值会更新,并且子组件中的 `theme` 值也会相应地更新。 这就是一个简单的 React 上下文共享变量的案例,通过这种方式,我们可以避免通过层层传递 props 来实现变量共享的繁琐过程,并将变量存储在上下文中,让需要使用该变量的组件可以方便地获取到它。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值