我目前有几个在功能方面看起来相似的 React 组件。它们都有相似的方法,用于从服务器获取数据并通过为不同端点创建 API 来更新每个组件的状态。
import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';
import AppService from '../lib/service';
class Factorial extends Component {
constructor(props) {
super(props);
this.state = {
value: '',
}
}
getNext() {
AppService.getNextFactorial().then(data => {
this.setState({ value: data.data.gen })
})
}
resetFactorial() {
AppService.resetNextFactorial().then(data => {
this.setState({ value: data.data.reset })
})
}
render() {
return (
<div className={'functionsWrapper'}>
<h2> Factorial Sequence Generator </h2>
<p> Click to get the next value in the sequence </p>
<button onClick={() => this.getNext()}> Get Next</button>
<button onClick={() => this.resetFactorial()}> Reset </button>
<div>
<input type="text" id="body" defaultValue={this.state.value} name="body" className="form-input" />
</div>
</div>
)
}
}
export default withRouter(Factorial);
import React, { Component } from 'react';
import AppService from '../lib/service';
class Fibonacci extends Component {
constructor(props) {
super(props);
this.state = {
value: '',
}
}
getNext() {
AppService.getNextFibonacci().then(data => {
this.setState({ value: data.data.gen })
})
}
resetFibonacci() {
AppService.resetNextFibonacci().then(data => {
this.setState({ value: data.data.reset })
})
}
render() {
return (
<div className={'functionsWrapper'}>
<h2> Fibonacci Sequence Generator </h2>
<p> Click to get the next value in the sequence </p>
<button onClick={() => this.getNext()}> Get Next</button>
<button onClick={() => this.resetFibonacci()}> Reset </button>
<div>
<input type="text" id="body" defaultValue={this.state.value} name="body" className="form-input" />
</div>
</div>
)
}
}
export default Fibonacci;
我想要实现的是能够拆分每个组件的功能并使其可重用,以便我可以拥有通用的方法
最佳答案
helper.js
import AppService from '../lib/service';
export function resetFibonacci() {
AppService.resetNextFibonacci().then(data => {
this.setState({ value: data.data.reset })
});
}
NOTE: use function insted of an arrow function "() => {}"
Fibonacci.js(您的组件)
import * as Helpers from './helpers.js';
...
resetFibonacci() {
Helpers.resetFibonacci.call(this);
}
NOTE: bind this to the function scope.
关于javascript - 如何使用通用方法通过重用代码来定义 React 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54165930/