Reactjs 从两个不同的组件更新相同的变量

Reactjs 从两个不同的组件更新相同的变量,reactjs,react-jsx,Reactjs,React Jsx,我想使用相同的状态变量,比如count和update,并检索更新后的变量 我编写了以下代码作为一个高阶组件,由一个按钮和一个标签组成。两者都会更新计数,但它们有单独的实例。那么,如何重新调整代码以保持变量计数的相同副本呢 const HOC = (InnerComponent) => class extends React.Component{ constructor(){ super(); this.state = { co

我想使用相同的状态变量,比如count和update,并检索更新后的变量

我编写了以下代码作为一个高阶组件,由一个按钮和一个标签组成。两者都会更新计数,但它们有单独的实例。那么,如何重新调整代码以保持变量计数的相同副本呢

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;
const HOC=(InnerComponent)=>类扩展React.Component{
构造函数(){
超级();
此.state={
计数:0
}
}
更新(){
this.setState({count:this.state.count+1})
}
render(){
返回(
)
}
};
类应用程序扩展了React.Component{
render(){
返回(
按钮

标签 ); } } const Button=HOC((props)=>{props.children}-{props.count}) 类标签扩展了React.Component{ render(){ 返回( {this.props.children}-{this.props.count} ) } } 常量LabelHOC=HOC(标签) 导出默认应用程序;
您需要执行一些“操作”

React只是一个渲染库,它渲染状态,因此您需要考虑该状态应该位于何处。通常情况下,您的场景会开始查看某种通量库,该库可以处理“一个真相来源”(将您的状态保持在一个位置),例如。如果您使用的是Redux,那么Redux存储将为这两个组件保留“计数”状态,并且它们都可以更新和读取它,因此从长远来看,这将是我的建议。但是为了解决您眼前的问题,您必须让更高的组件保持状态,然后当然也修改该状态,您可以通过将状态和更新函数作为道具传递给子级来实现这一点

这是它的外观片段,只需将状态(count)和更新函数向下发送到子组件。我排除了HOC组件,因为我认为它只是增加了您在这里的困惑。但我相信你可以想象它是如何工作的

类应用程序扩展了React.Component{
构造函数(){
超级();
此.state={
计数:0
}
this.update=this.update.bind(this);//绑定一次
}
更新(){
this.setState({count:this.state.count+1})
}
render(){
返回(
按钮

标签 ); } }
从文件中可以看出:


太棒了!我对你回答的前半部分感到满意。我会回来用Redux实现它。
class App extends React.Component {
    constructor(){
        super();
        this.state = {
            count: 0
        }
     this.update = this.update.bind(this); //Bind it once
    }
    update(){
        this.setState({count: this.state.count + 1})
    }
    render() {
        return (
            <div>
                <Button count={this.state.count} update={this.update}>Button</Button>
                <hr />
                <LabelHOC count={this.state.count} update={this.update}>Label</LabelHOC>
            </div>
        );
    }
}