我有一个正在从事的项目是为了了解反应路线。我有几个组成部分,但我只想集中讨论两个,一个组成部分增加了硬币的数量(购买),而另一个减少了硬币的数量(出售)。我无法理解高阶组件将如何帮助我显示两个组件中的数据。如果有另一种解决方案,那就太好了。这是两个组件。
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
我将处理答案字母,其他内容相同,只是减少硬币。
答案 0 :(得分:0)
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如何适合这种情况,但不适用于您的情况。