React 组件内的导出函数或组件外同一文件中的访问状态

2024-06-26

我有一个需要从文件中导出的函数,但同时,我需要在更新时利用反应状态重新渲染。

似乎不太可能从类内部导出函数,那么如何从类外部的函数更新状态呢?

import React, {Component} from 'react';

export function functionName(){
const filter = some filter;
  this.setState({
    filter: newFilter
  })
}

class ClassName extends Component{
  constructor(){
    super();
    this.state = {
      filter: {}
    }
  }
  render(){
    <>
    </>
  }
}

您可以导出functionName到外面,但你无权访问this.setState在该函数内。

所以你可能想要做到pure,返回一个新的状态。 请参阅 Dan Abramov 的这篇技巧 -https://twitter.com/dan_abramov/status/824308413559668744?lang=en https://twitter.com/dan_abramov/status/824308413559668744?lang=en

所以让我们做一些有趣的事情吧functionName按照 Dan 的提示可重复使用。


You can follow along with a working demo below.
Edit so.answer.57417643


在下面的代码中,increment & decrement匹配到functionName从你的帖子。更新状态的函数(但实际上返回一个新状态)。

Counter匹配你的ClassName,其中,您想要重新使用正在导出的函数。

重用导出函数的方法是调用this.setState within Counter(参考handleIncrement/handleDecrement).

import React, { Component } from "react";

// https://twitter.com/dan_abramov/status/824308413559668744/photo/1
export const increment = (state, props) => ({
  value: state.value + 1
});
export const decrement = (state, props) => ({
  value: state.value - 1
});

class Counter extends Component {
  state = { value: 0 };

  handleIncrement = () => this.setState(increment);
  handleDecrement = () => this.setState(decrement);

  render() {
    const { value } = this.state;

    return (
      <>
        <h1>Counter.jsx: {value}</h1>
        <button onClick={this.handleIncrement}>+</button>
        <button onClick={this.handleDecrement}>-</button>
      </>
    );
  }
}

export default Counter;

Now Counter, increment, and decrement可以出口并可以在其他地方进口。

import React, { useState } from "react";
import Counter, { increment, decrement } from "./Counter";

function App() {
  const [count, setCount] = useState({ value: 0 });

  //                      ... Being reused! ????
  const handleIncrement = () => setCount(increment);
  const handleDecrement = () => setCount(decrement);

  return (
    <div className="App">
      <section>
        <h1>App: {count.value}</h1>
        <button onClick={handleIncrement}>+</button>
        <button onClick={handleDecrement}>-</button>
      </section>

      <section>
       {/* ???? We can use the counter as it is */}
        <Counter />
      </section>
    </div>
  );
}

您可以将其导入到另一个文件中,然后使用Counter按原样使用或重复使用increment/decrement也在函数组件内部。

这意味着,您可以在类和函数组件中使用相同的逻辑! ????

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

React 组件内的导出函数或组件外同一文件中的访问状态 的相关文章

随机推荐