同じ状態変数count countを使用して、更新された変数を取得して取得したいと考えています。2つの異なるコンポーネントから同じ変数を更新する
1つのボタンと1つのラベルからなる上位コンポーネントとして次のコードを記述しました。どちらもカウントを更新しますが、別々のインスタンスがあります。では、変数の同じコピーを保持するためにコードを再整列する方法を教えてください。
const HOC = (InnerComponent) => class extends React.Component{
constructor(){
super();
this.state = {
count: 0
}
}
update(){
this.setState({count: this.state.count + 1})
}
render(){
return(
<InnerComponent
{...this.props}
{...this.state}
update = {this.update.bind(this)}
/>
)
}
};
class App extends React.Component {
render() {
return (
<div>
<Button>Button</Button>
<hr />
<LabelHOC>Label</LabelHOC>
</div>
);
}
}
const Button = HOC((props) => <button onClick={props.update}>{props.children} - {props.count}</button>)
class Label extends React.Component{
render(){
return(
<label onMouseMove={this.props.update}>{this.props.children} - {this.props.count}</label>
)
}
}
const LabelHOC = HOC(Label)
export default App;
ブリリアント!私はあなたの答えの前半で満足しています。私は戻ってReduxで実装します。 – kushalvm