javascript - 高阶组件(HOC)
问题描述
为了理解反应路由,我正在开发一个项目。我有几个组件,但我只想关注两个,一个组件增加硬币的数量(买入),另一个减少硬币的数量(卖出)。我无法理解高阶组件如何帮助我显示来自两个组件的数据。如果有另一种方法来解决这个问题,那就太好了。这是其中的两个组件。
import React, {Component} from 'react';
class Mine extends Component {
constructor(props){
super(props);
this.state = {
coins: 0,
answer: ""
}
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit = (event) => {
event.preventDefault();
this.setState({coins: this.state.coins + 1})
console.log("Your Answer: " + this.state.answer + " and coins: " + this.state.coins);
}
handleChange = (event) => {
this.setState({[event.target.name]: event.target.value});
console.log(this.state.answer);
}
render() {
const {answer} = this.state;
const isEnabled = answer.length > 0;
return (
<div>
<h1>Mine Shinto Coins</h1>
<p>Here you can Mine shinto Coins by being the first to solve the algorithom.</p>
<p>What is the 7th Fibonacci sequence Number?</p>
<form onSubmit={this.handleSubmit}>
<input type="text" name = "answer" onChange = {this.handleChange}/>
<input type="submit" value="Mine" disabled = {!isEnabled}/>
</form>
</div>
)
}
}
export default Mine
我会处理答案信,其他部分是一样的,只是减少硬币。
解决方案
function withCoinDeal(Component, howChange) {
return class extends React.Component {
state = {
coins: 0
}
handleChange = this.handleChange.bind(this)
componentDidMount() {
DataSource.addChangeListener(this.handleChange);
}
componentWillUnmount() {
DataSource.removeChangeListener(this.handleChange);
}
handleChange() {
this.setState({
coins: howChange(DataSource, this.props)
});
}
render() {
return <Component coins={this.state.coins} {...this.props} />;
}
};
}
上面的示例显示了 HOC 如何适合这种情况,但不适用于您的情况。