您可以导出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](https://codesandbox.io/static/img/play-codesandbox.svg)
在下面的代码中,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
也在函数组件内部。
这意味着,您可以在类和函数组件中使用相同的逻辑!
????